Is it possible to persist using Svelte right now? #5378
-
Svelte lover here: is it possible to persist with Svelte too? Or is just for React for now? If not this is a blocking for us unfortunately. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 14 replies
-
The react adapter is pretty slim, you can take a look here: I think you can do that in svelte in user-land and then maybe contribute it back as a |
Beta Was this translation helpful? Give feedback.
-
@frederikhors, i was able to persist and load client with this when disabling ssr ( might also work with ssr). Let me know if this worked? BTW I'm not using the query-persist-core because it rewrites every time the query cache changes, and I think frequently JSON.stringify-ing and writing the local storage might slows down my app ( I maybe wrong here ), so what i did here was saved the query state on unload. This only works when the function is non asynchronous and writing to local storage is synchronous. <script>
import { setContext, onMount } from "svelte";
import { hydrate, dehydrate } from "@tanstack/svelte-query";
import { SvelteQueryDevtools } from "@tanstack/svelte-query-devtools";
export let data;
const queryClient = data.queryClient;
setContext("$$_queryClient", queryClient);
const hydrateClient = () => {
try {
const storeValue = localStorage.getItem("QUERY_CLIENT");
if (!storeValue) return;
const persistedValue = JSON.parse(storeValue);
if (persistedValue?.timestamp) {
const MAX_AGE = 1000 * 60 * 60 * 24;
const expired = Date.now() - persistedValue.timestamp > MAX_AGE;
if (!expired) hydrate(queryClient, persistedValue.clientState);
} else {
localStorage.removeItem("QUERY_CLIENT");
}
} catch {
// remove persisted client on any error
localStorage.removeItem("QUERY_CLIENT");
}
};
const saveClient = () => {
localStorage.setItem(
"QUERY_CLIENT",
JSON.stringify({
timestamp: Date.now(),
clientState: dehydrate(queryClient, {})
})
);
};
const unload = () => {
saveClient();
};
onMount(() => {
hydrateClient();
queryClient.mount();
return () => {
queryClient.unmount();
};
});
</script>
<slot />
<SvelteQueryDevtools buttonPosition="bottom-right" />
<svelte:window on:beforeunload={unload} /> |
Beta Was this translation helpful? Give feedback.
-
Thats promise.then(() => {}) |
Beta Was this translation helpful? Give feedback.
@frederikhors, i was able to persist and load client with this when disabling ssr ( might also work with ssr). Let me know if this worked? BTW I'm not using the query-persist-core because it rewrites every time the query cache changes, and I think frequently JSON.stringify-ing and writing the local storage might slows down my app ( I maybe wrong here ), so what i did here was saved the query state on unload. This only works when the function is non asynchronous and writing to local storage is synchronous.