T
TanStack3y ago
harsh-harlequin

InvalidatateQuery problem

Custom Hooks
export const useAddUnitMutation = () => {
const { queryClient } = useQueryClientInstance();

return useMutation({
mutationFn: (payload: TUnitPayload) => {
return unitsAPI.createUnit(payload)
},
onSuccess: () => {
toast.success('New unit added successfully');
return queryClient.invalidateQueries(['units']);
},
onError: error => errorHandler(error),
});
};
export const useAddUnitMutation = () => {
const { queryClient } = useQueryClientInstance();

return useMutation({
mutationFn: (payload: TUnitPayload) => {
return unitsAPI.createUnit(payload)
},
onSuccess: () => {
toast.success('New unit added successfully');
return queryClient.invalidateQueries(['units']);
},
onError: error => errorHandler(error),
});
};
export const useUnits = (params?: ApiParams, options?: QueryOpt<Paginated<TUnit>>) => {
return useQuery({
queryKey: ['units', params],
queryFn: () => unitsAPI.getUnits(params).then(res => res.data),
...options,
});
};
export const useUnits = (params?: ApiParams, options?: QueryOpt<Paginated<TUnit>>) => {
return useQuery({
queryKey: ['units', params],
queryFn: () => unitsAPI.getUnits(params).then(res => res.data),
...options,
});
};
const handleUnitSubmit = async (payload: TUnitPayload) => {
try {
await create.mutateAsync(payload);

reset();
router.push(ROUTES.Units);
return sleep();
} catch (error) {
errorHandler(error);
}
};
const handleUnitSubmit = async (payload: TUnitPayload) => {
try {
await create.mutateAsync(payload);

reset();
router.push(ROUTES.Units);
return sleep();
} catch (error) {
errorHandler(error);
}
};
I fetch useUnits in Units page and I used useAddUnitMutation in AddUnit page. So whenever I navigate to AddUnit page the units queryKey is inactive which is expected. My problem here is that whenever I invalidate the units and navigate back to Units page, the list of units is not updated but it is still the old data. As of now I used refetchQueries instead of invalidateQueries but I don't know if this is okay or not. Also, I am using NextJS 13 app & tanstack-query v4
6 Replies
harsh-harlequin
harsh-harlequinOP3y ago
Provider
function AppQueryClientWrapper({ children }: { children: React.ReactNode }) {
const { queryClient } = useQueryClientInstance();

return (
<QueryClientProvider client={queryClient}>
{children}
{process.env.NODE_ENV !== 'production' && <ReactQueryDevtools initialIsOpen={false} />}
</QueryClientProvider>
);
}

function ReactQueryProvider({ children }: { children: React.ReactNode }) {
return (
<QueryClientInstanceProvider>
<AppQueryClientWrapper>{children}</AppQueryClientWrapper>
</QueryClientInstanceProvider>
);
}

export default ReactQueryProvider;
function AppQueryClientWrapper({ children }: { children: React.ReactNode }) {
const { queryClient } = useQueryClientInstance();

return (
<QueryClientProvider client={queryClient}>
{children}
{process.env.NODE_ENV !== 'production' && <ReactQueryDevtools initialIsOpen={false} />}
</QueryClientProvider>
);
}

function ReactQueryProvider({ children }: { children: React.ReactNode }) {
return (
<QueryClientInstanceProvider>
<AppQueryClientWrapper>{children}</AppQueryClientWrapper>
</QueryClientInstanceProvider>
);
}

export default ReactQueryProvider;
Context
export const QueryClientInstanceContext = createContext<{ queryClient: QueryClient | null }>({
queryClient: null,
});

export const QueryClientInstanceProvider = ({ children }: { children: ReactNode }) => {
const [queryClient] = useState(() => new QueryClient(QUERY_CLIENT_OPTIONS));

return (
<QueryClientInstanceContext.Provider value={{ queryClient }}>
{children}
</QueryClientInstanceContext.Provider>
);
};



export const useQueryClientInstance = (): { queryClient: QueryClient } => {
const { queryClient } = useContext(QueryClientInstanceContext);

if (!queryClient) {
throw new Error('No QueryClientInstanceProvider found');
}

return { queryClient };
};
export const QueryClientInstanceContext = createContext<{ queryClient: QueryClient | null }>({
queryClient: null,
});

export const QueryClientInstanceProvider = ({ children }: { children: ReactNode }) => {
const [queryClient] = useState(() => new QueryClient(QUERY_CLIENT_OPTIONS));

return (
<QueryClientInstanceContext.Provider value={{ queryClient }}>
{children}
</QueryClientInstanceContext.Provider>
);
};



export const useQueryClientInstance = (): { queryClient: QueryClient } => {
const { queryClient } = useContext(QueryClientInstanceContext);

if (!queryClient) {
throw new Error('No QueryClientInstanceProvider found');
}

return { queryClient };
};
Root Layout
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className="h-full">
<body className={cn(manrope.className)}>
<Toaster
position="top-center"
toastOptions={{ duration: 6000 }}
containerClassName="py-0"
/>
<NextAuthProvider>
<ReactQueryProvider>{children}</ReactQueryProvider>
</NextAuthProvider>
</body>
</html>
);
}
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className="h-full">
<body className={cn(manrope.className)}>
<Toaster
position="top-center"
toastOptions={{ duration: 6000 }}
containerClassName="py-0"
/>
<NextAuthProvider>
<ReactQueryProvider>{children}</ReactQueryProvider>
</NextAuthProvider>
</body>
</html>
);
}
export const QUERY_CLIENT_OPTIONS = {
defaultOptions: {
queries: { staleTime: 5000, refetchOnWindowFocus: false, refetchOnMount: false, retry: 1 },
},
};
export const QUERY_CLIENT_OPTIONS = {
defaultOptions: {
queries: { staleTime: 5000, refetchOnWindowFocus: false, refetchOnMount: false, retry: 1 },
},
};
foreign-sapphire
foreign-sapphire3y ago
refetchOnMount: false prevents stale queries to refetch when you navigate between pages (=when the component mounts). So you've opted out of that, which makes it "not work"
harsh-harlequin
harsh-harlequinOP3y ago
Is there a way that I can only refetchOnMount once invalidateQueries triggers?
foreign-sapphire
foreign-sapphire3y ago
no, that's what staleTime is for.
absent-sapphire
absent-sapphire3y ago
You could removeQueries instead of invalidate, right?
harsh-harlequin
harsh-harlequinOP3y ago
ohh okayy now I get it, thank youu :))

Did you find this page helpful?