I'm trying to use reactquery's persister with nextjs, but when I start the page it throws an error: " ReferenceError: window is not defined "
queryClient.ts:
import { QueryClient } from "react-query";
import { createWebStoragePersistor } from "react-query/createWebStoragePersistor-experimental";
import { persistQueryClient } from "react-query/persistQueryClient-experimental";
const cacheTime = 1000 * 60 * 60 * 24 * 5; // 5 dias
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
cacheTime,
},
},
});
const localStoragePersistor = createWebStoragePersistor({
storage: window.localStorage,
});
persistQueryClient({
queryClient,
persistor: localStoragePersistor,
maxAge: cacheTime,
});
_app.tsx:
import type { AppProps } from "next/app";
import "../styles/globals.css";
import { QueryClientProvider } from "react-query";
import { PokeDataContextProvider } from "@/context/PokeData";
import { queryClient } from "@/services/queryClient";
export default function App({ Component, pageProps }: AppProps) {
return (
<QueryClientProvider client={queryClient}>
<PokeDataContextProvider>
<Component {...pageProps} />
</PokeDataContextProvider>
</QueryClientProvider>
);
}
I already tried using if(typeof window !== 'undefined') in all the places I could think of, and I couldn't solve this problem.
we allow to pass undefined as storage for SSR because restore from persistence happens in an effect (which doesn't run on the server) anyway:
const localStoragePersistor = createWebStoragePersistor({
storage: typeof window !== 'undefined' ? window.localStorage : undefined,
});
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