[feat] helper for creating stores
See original GitHub issueDescribe the problem
You can’t just blindly create a store in SSR or it’ll end up being a global store shared by all users (https://github.com/sveltejs/kit/discussions/4339). We should provide a helper that ties it to the request.
Describe the proposed solution
At the very least we can make it part of the Svelte context. SvelteKit does this internally with its own stores.
I wonder if we couldn’t make it available earlier. If we only make it part of the Svelte context then you can’t use it in load
. If we additionally tied it to the request it would be available throughout the rendering of the request.
We could have an API like:
export const getStore = function(key, request) {
return request ? WEAK_MAP.get(request).get(key) : getContext(key);
};
When we’re going to start rendering the templates we could populate the context from the map.
We could also have a method to create a store. Being able to call it in handle
would solve https://github.com/sveltejs/kit/issues/7107:
createStore(request, 'whatever', request.locals.whatever);
There are a couple things we might make optional. E.g. we could potentially look for 'whatever'
in locals
automatically. Or we could make the request optional - if it’s not provided the store would only be available in the template (at least on the server).
Alternatives considered
The user could create the store themselves if we just want it available in the template. That starts getting cumbersome if they want it available either as a singleton in the browser or tied to the request on the server. It’s impossible if they want to populate it from locals
Some of the APIs I’ve proposed here may be open for debate on the actual details
Importance
would make my life easier
Additional Information
No response
Issue Analytics
- State:
- Created a year ago
- Reactions:18
- Comments:19 (19 by maintainers)
I long wanted to write a “State Management” section for the docs, where we also can note the “careful what to put on the server, it’s shared for all requests”-stuff. This pattern could also go in there.
An issue i´ve run into a few times now is not beeing able to update
$page.data
client side.Example:
You display some database rows in your app and add another row. You call
fetch
and post the data to a+server
endpoint or make use of the form actions. The only option (that i know of) to get the added row is to callinvalidate
and reload all page related data. This will obviously result in twice the network calls compared to just adding the newly created data to$page.data
.One way i´ve solved this:
make it a store in
+page.ts
and update that store inside
+page.svelte
I´m just curious if this api/helper, if it´s going to be a thing, will provide an easier way to get writable stores from the client to the server in such use cases.