I'm using React Query to fetch data based on a user's active organization. A user has the ability to switch the organization for which they're viewing the data of, therefore when the value of user.activeOrg changes, I want the query client to refetch its queries with the new organization as the value to fetch from. However, because the function is initialized with the user's default org as the initial value, when the useEffect fires it still fetches data from the original organization.
Is there a way I can declare dependencies for the useQuery hook so that it refreshes its query with the user.activeOrg value changes? I know that you can use the enabled option to force the hook to wait until a certain value exists before becoming active (seen in my invocation of useQuery below) but I can't find a way to provide additional variables for the hook to depend on. Any help is appreciated. Thanks.
const { user } = useActiveUser();
const queryClient = useQueryClient();
const getData = async () => {
const data = await OrgService.getOrgData(user.activeOrg);
return data;
};
const { data } = useQuery('orgData', getData, { enabled: !!user });
useEffect(() => {
if (!user) return;
queryClient.refetchQueries();
}, [user?.activeOrg]);
For anyone who comes across this, I ended up finding the fix after reading up this page in the documentation. You can pass variables into your query functions along with your query key to fetch dynamically, no refetching necessary:
const { user } = useActiveUser();
const getData = async ({ queryKey }) => {
const [_key, { activeUser }] = queryKey;
const data = await OrgService.getOrgData(activeUser.activeOrg);
return data;
};
const { data } = useQuery(['orgData', { activeUser: user }], getData, { enabled: !!user });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With