-
What is the best way to avoid a Hydration Mismatch on the first page load using makePersisted? Ideally, makePersisted would wait until the dom isHyrated before it changes its default to the value stored in storage. This renders fine on the first page load: const [getUsers, setUsers] = makePersisted(
createSignal<string[]>([]),
{storage: globalThis.sessionStorage, name: 'users'}
) <button onClick={()=> {setUsers(['user1'])}}>Add</button>
<For each={getUsers()}>
{user=> <>
<button class="btn join-item">
{user}
</button>
</>}
</For> Now, refresh the browser and the server will render no users, however, the 1st render on the client will render one user which causes the Hydration Mismatch. I'll make a reproduction if you think I'm in error, I'm summarizing code. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I' am afraid this is failure by design. The hydration expects the same element to render on the server and the client, but the client has the users from session storage faster than the server, which leads to a mismatch. Our primitive behaves exactly as specified, but that becomes an issue with hydration. How to solve this? In theory, you could block the rendering until hydration is done. Let me think about how to do this. As a workaround, you could use a memo to return an empty array until hydration. We have a nifty little lifecycle primitive you might find helpful. I might add an option where you can add an accessor that will let us block updates until truthy. Update: I added the option. Once the PR is merged, you can use isHydrated from lifecycle inside the options to avoid hydration errors. |
Beta Was this translation helpful? Give feedback.
I' am afraid this is failure by design. The hydration expects the same element to render on the server and the client, but the client has the users from session storage faster than the server, which leads to a mismatch. Our primitive behaves exactly as specified, but that becomes an issue with hydration.
How to solve this? In theory, you could block the rendering until hydration is done. Let me think about how to do this. As a workaround, you could use a memo to return an empty array until hydration. We have a nifty little lifecycle primitive you might find helpful. I might add an option where you can add an accessor that will let us block updates until truthy.
Update: I added the option.…