Global store in Solid Start app

Hey, I recently thought to myself that I haven't really done a proper e-commerce app yet that would fill my portfolio. So I decided I would make an e-commerce app with a little bit of a challenge, basically instead of using any SPA framework (React, Solid etc.) I wanted to try Solid Start. At first the experience was great (create-jd-app ❤️ ) however I wanted to implement a cart for the app. I read the Solid Start docs however I was discouraged on using global state. I remember using zustand a lot for any global state applications where I had to synchronise some data between components. And that begs the question, how should I implement a reactive cart, that would influence my navbar (basically showing the number of items in the cart) and would basically be synchronised around my app?
1 Reply
andi
andi14mo ago
so in a server context, there is only one instance of the solid library managing things, just like there's only one instance running for a client on a webpage if you think of solid like a container, all requests from different clients go in the same container that means that any global state you have will be shared between all clients, which you generally don't want to do because each user should only have access and modify to their own data
export const [globalState, setGlobalState] = createStore({});

// any user requesting the page with this component will receive the same number, since they're all sharing the global state
<div>{globalState.cartItems.length}</div>
export const [globalState, setGlobalState] = createStore({});

// any user requesting the page with this component will receive the same number, since they're all sharing the global state
<div>{globalState.cartItems.length}</div>
the solution to that is to put your global state in a place where it gets created separately for each different request the recommended way to do it in solid-start would be to create a new store somewhere inside the root.tsx component, and passing it to children with a context provider if you do it like that, you can't import the state directly anymore, you have to use a useContext hook
Want results from more Discord servers?
Add your server