-
I currently have a web application where I have multiple queries that depend on an access token in order to authenticate against an external api. I fetch this access token from my server once the user loads the app. I want all the queries that rely on this access token to not run until I've fetched and set the access token. It seems that with Codesandbox for [email protected] (Works on this version) App.tsx import { Users } from "./Users";
import {
QueryClient,
QueryClientProvider,
useQueryClient
} from "@tanstack/react-query";
import { useEffect } from "react";
import { getAccessToken, setAuthToken } from "./http";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
enabled: false
}
}
});
const EnableQueriesWhenHasAccessToken = () => {
const queryClient = useQueryClient();
useEffect(() => {
getAccessToken()
.then((token) => setAuthToken(token))
.then(() => {
queryClient.setDefaultOptions({
queries: {
enabled: true
}
});
queryClient.refetchQueries();
});
}, [queryClient]);
return null;
};
export default function App() {
return (
<div className="App">
<QueryClientProvider client={queryClient}>
<EnableQueriesWhenHasAccessToken />
<Users />
</QueryClientProvider>
</div>
);
} Users.tsx import { useQuery } from "@tanstack/react-query";
import { getUsers } from "./http";
const useUsersQuery = () => useQuery(["users"], getUsers);
export const Users = () => {
const { data: users, isLoading } = useUsersQuery();
if (isLoading || !users) {
return <p>Loading users...</p>;
}
return (
<div>
<h3>Users:</h3>
{users.map((user) => (
<p key={user.id}>{user.name}</p>
))}
</div>
);
}; let token: string | null = null;
export const setAuthToken = (accessToken: string) => {
token = accessToken;
};
export const getUsers = (): Promise<{ id: number; name: string }[]> => {
console.log("Calling get users endpoint with access token", token);
return new Promise((resolve) => {
setTimeout(() => {
resolve([
{
id: 1,
name: "John"
},
{
id: 2,
name: "Jane"
}
]);
}, 1000);
});
};
export const getAccessToken = (): Promise<string> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve("MY_ACCESS_TOKEN");
}, 1000);
});
}; |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
changing defaultOptions has no effect on queries that have already been created. What could work is making the |
Beta Was this translation helpful? Give feedback.
changing defaultOptions has no effect on queries that have already been created. What could work is making the
Users
component a child ofEnableQueriesWhenHasAccessToken
and to render it conditionally, only after the token has been obtained.