T
TanStack2y ago
automatic-azure

I have a problem with authentication using React Query.

Hey guys, a I'm newbie in React Query but i want to convert my app from Redux Toolkit to React Query. I want to save data when user click submit button in login form and after that change app to authenticated version in my root component. I don't know where i am doing something bad, but i have always my token undefined. I am hoping that you guys help me <3. import { useMutation, useQueryClient } from "react-query"; import axios from "axios"; export const useLoginUser = () => { const queryClient = useQueryClient(); return useMutation( async ({ username, password }: { username: string; password: string }) => { const url = ${import.meta.env.VITE_API_KEY}/login; const { status, data } = await axios.post(url, { username, password, }); if (status === 200) { const { token, user } = data; return { success: true, token, user }; } else { console.error("Unexpected response status:", status); return { success: false }; } }, { onSuccess: async (data) => { if (data.success) { const { token, user } = data; await queryClient.invalidateQueries("user", user); await queryClient.invalidateQueries("accessToken", token); } }, }, ); }; import { useQueryClient } from "react-query"; import { AuthenticatedApp } from "./AuthenticatedApp.tsx"; import { UnauthenticatedApp } from "./UnauthenticatedApp.tsx"; export const Root = () => { const queryClient = useQueryClient(); const token = queryClient.getQueryData("accessToken"); return token ? <AuthenticatedApp /> : <UnauthenticatedApp />; };
1 Reply
optimistic-gold
optimistic-gold2y ago
Calling queryClient.getQueryData in a component is not good, because it's not a subscription and your component won't re-render. This is like calling getState() of redux instead of calling useSelector. You want useQuery there

Did you find this page helpful?