Replies: 2 comments
-
I'm running into a similar issue in my Next.js app. The closest I've come is a solution similar to yours where I have a store action that does the fetching. I am, however, still looking for a cleaner solution, as this feels very messy. It would be great if you could just await store creation so you could call await directly in the store. This way you always know that if your store exists, it has the initial data it needs. And you also would not have to track some sort of "isInitialized" value anymore. |
Beta Was this translation helpful? Give feedback.
-
@szimek inside the provider i can then use an useEffect hook to fetch data and create the store. The provider ends up looking something like this
|
Beta Was this translation helpful? Give feedback.
-
Hi!
I'm sure some version of this question has been asked and answered already, but here it is.
The first part of the question is store initialization with data from the server (or any async source). I have a client-side rendered React app and I want to initialize the store with some ids from query params. However, before I do it, I need to validate these ids with user's data that I need to fetch from the server first. In my case this means using TanStack Query and either
useQuery
hook (what we use at the moment) orqueryClient.fetchQuery
call (if needed to be done outside our a React component).The second part is syncing store state with query params. Whenever these validated ids in the store change (e.g. during the initialization or later when they are added or removed by the user), I want to update query params as well.
Regarding the store initialization - what's the best way to do it? Are async actions the recommended way to do it? This is close to the example from the docs:
How to ensure it happens only once? Where to put it - in the function that creates the store, or in some
useEffect
that ensures everything runs only once?What about any other action that might be called and try to modify the store state while the store is being initialized - should it be allowed, ignored, queued? Should there be an additional
status
prop that indicates if the initialization is pending, successful or failed that other actions take into account? I probably could put the async initialization call in the route loader, but I don't necessarily want to block loading of the page while the data needed to validate these ids is fetched from the server.Regarding syncing store state with query params - what's the best way to do it? Middleware similar to
persist
? Maybe use theusePrevious
hook to compare the previous and current state? Or maybe subscribe to the whole store inuseEffect
and update params there?Beta Was this translation helpful? Give feedback.
All reactions