Skip to content

Instantly share code, notes, and snippets.

@dipeshdulal
Created April 13, 2021 06:17
Show Gist options
  • Save dipeshdulal/39f4e06c0f02789320c41b0d87863f24 to your computer and use it in GitHub Desktop.
Save dipeshdulal/39f4e06c0f02789320c41b0d87863f24 to your computer and use it in GitHub Desktop.
React Query QueryClient Persistence

Using dehydrate and hydrate function we can persist react query cache in localStorage or AsyncStorage in case of react-native.

Basic implementation for persistence can be made by attaching subscribe function to queryCache and upon new data store the data to persistence layer and upon the app start the persisted cache can be rehydrated.

import AsyncStorage from "@react-native-community/async-storage";
import { QueryCache, QueryClient } from "react-query";
import { dehydrate, hydrate } from "react-query/hydration";
import { jsonParse } from "../utils/jsonParse";
export const queryCache = new QueryCache();
const queryClient = new QueryClient({
queryCache: queryCache,
});
let firstTime = true;
const hydrateFromAsyncStorage = async () => {
const state = await AsyncStorage.getItem("@react-query-cache");
const parsedState = jsonParse(state ?? "{}");
hydrate(queryClient, parsedState);
};
queryCache.subscribe(async () => {
if (firstTime) {
await hydrateFromAsyncStorage();
}
const dehydratedState = dehydrate(queryClient, {
dehydrateQueries: true,
dehydrateMutations: false,
});
AsyncStorage.setItem("@react-query-cache", JSON.stringify(dehydratedState));
firstTime = false;
});
export { queryClient };
@bibek-magar
Copy link

🙇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment