Why useQuery runs multiple times?

my first time of using react query and facing issue of running API request multiple times, I dont know what causes this issue am I doing anything wrong?
export const sendAuth = async ({ token }: { token?: string }) => {
return axiosInstace()
.post("/adminTokenVerify", { token })
.then((res) => res.data);
};

export const useAdminAuth = () => {
const [clientId, setClientId] = useState<string>("");
const [email, setEmail] = useState<string>("");
const [auth, setAuth] = useState<AUTH_STAGES>(AUTH_STAGES.AUTHORIZED);

const token = localStorage.getItem(TOKEN_STORAGE_KEY.TOKEN);

const { data } = useQuery(
["auth"],
() => sendAuth({ token: JSON.parse(token!) })
);

return { clientId, email, auth };
};
export const sendAuth = async ({ token }: { token?: string }) => {
return axiosInstace()
.post("/adminTokenVerify", { token })
.then((res) => res.data);
};

export const useAdminAuth = () => {
const [clientId, setClientId] = useState<string>("");
const [email, setEmail] = useState<string>("");
const [auth, setAuth] = useState<AUTH_STAGES>(AUTH_STAGES.AUTHORIZED);

const token = localStorage.getItem(TOKEN_STORAGE_KEY.TOKEN);

const { data } = useQuery(
["auth"],
() => sendAuth({ token: JSON.parse(token!) })
);

return { clientId, email, auth };
};
8 Replies
yaviscoke
yaviscoke•2y ago
I use it in provider
import { AuthContext } from "context/AuthContext";
import { useAdminAuth } from "./hook/useAdminAuth";

export const AuthProvider = ({ children }: React.PropsWithChildren) => {
const { auth, clientId, email } = useAdminAuth();

return (
<AuthContext.Provider
value={{
clientId,
email,
auth,
}}
>
{children}
</AuthContext.Provider>
);
};
import { AuthContext } from "context/AuthContext";
import { useAdminAuth } from "./hook/useAdminAuth";

export const AuthProvider = ({ children }: React.PropsWithChildren) => {
const { auth, clientId, email } = useAdminAuth();

return (
<AuthContext.Provider
value={{
clientId,
email,
auth,
}}
>
{children}
</AuthContext.Provider>
);
};
Unknown User
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
yaviscoke
yaviscoke•2y ago
ohhh okay
dingo
dingo•2y ago
Another thing to add is that by default tRPC refetches on window focus & component remount (for queries). This means that whenever you click into another application and go back, it will refetch again, as well as when your component library unmounts and remounts a custom component.
Unknown User
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
dingo
dingo•2y ago
Huh, didn't know that, I think that relates to the refetch on focus 🙂
Unknown User
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
pandeyman
pandeyman•2y ago
yeah it works this way for every browser
Want results from more Discord servers?
Add your server