S
SolidJS5mo ago
cdegrel

LocalStorage Hydration Mismatch

I'm trying to display a component that should display the city name after retrieving it from localstorage, but i get this error Error: Hydration Mismatch. Unable to find DOM nodes for hydration key I use @solid-primitives/storage to keep the result of the API call in local storage and a Context to access it anywhere in my application. Can anyone help me understand what I'm doing wrong?
No description
No description
6 Replies
lxsmnsyc
lxsmnsyc5mo ago
your source for the createResource isn't consistent between server and client. Instead of doing isServer, you might want to use a signal that updates on the client e.g.
const [source, setSource] = createSignal(undefined);

createEffect(() => {
setSource(localStorage.getItem('my-item'));
});

const [data] = createResource(source, fetchData);
const [source, setSource] = createSignal(undefined);

createEffect(() => {
setSource(localStorage.getItem('my-item'));
});

const [data] = createResource(source, fetchData);
This is necessary so that the source is consistent between SSR and hydration. We defer reading from the local storage only after hydration is done (which is through createEffect)
cdegrel
cdegrelOP5mo ago
Thank you for the speed and explanation. I'm going to try it right away(Modifié)Restaurer la traduction d'origine but if I want to make the api call only if I don't have data in my localstorage, how can I proceed, sorry for the inconvenience, but this is the first time I'm on an ssr application my objective is to store the result of the call in localstorage, and when the browser is reloaded not to make another call if the data is present in the localstorage
Madaxen86
Madaxen865mo ago
Maybe something like:
onMount(async ()=>{
const storedItem = localstorage.getItem(…);
if (storeItem) return setSource(storeItem);
const res = await getGeolocationByID();
const location = await res.json();
setSource(location);
})
onMount(async ()=>{
const storedItem = localstorage.getItem(…);
if (storeItem) return setSource(storeItem);
const res = await getGeolocationByID();
const location = await res.json();
setSource(location);
})
cdegrel
cdegrelOP5mo ago
And to think it was that simple, thanks a lot you two 😃 .
Madaxen86
Madaxen865mo ago
Just thinking about it. Alternatively, you could use a cookie for persistence instead. If your fetch has credentials:“include“ it will be also available on the server. When dealing with SSR apps I usually persist only with cookies. The makePersistent primitive you used also provides a cookieStorage option. Just leaving this here if someone stumbles over it by searching. https://primitives.solidjs.community/package/storage
Solid Primitives
A library of high-quality primitives that extend SolidJS reactivity
cdegrel
cdegrelOP5mo ago
Thanks you for the info
Want results from more Discord servers?
Add your server