search

Home  >  Q&A  >  body text

The method of defining dynamic keys is in redux's initialState

<p>I have an e-commerce website where each user has a shopping cart and uses redux and redux persist to store in local storage. I want to handle multiple accounts on one computer, if a user has two accounts, he can switch between the accounts and the data related to each account will be displayed, my question is how to handle multiple accounts on one system accounts, each account has an id. I want to define this structure for the initial state: </p> <pre class="brush:php;toolbar:false;">const initialState = { [userId]:{ cart:[] } }</pre> <p>But I encountered an error</p> <p>For login, I use next-auth to handle it, and define this reducer to get the ID of the user when logging in. </p> <pre class="brush:php;toolbar:false;">addUserId: async (state, action) => { //Here I receive userId const session = await getSession(); console.log(session); },</pre>
P粉478835592P粉478835592455 days ago542

reply all(1)I'll reply

  • P粉245003607

    P粉2450036072023-09-06 13:25:14

    Since your initial state object has no defined properties, you can start with an empty initialState object. When you have data to populate your state, you can dynamically add the [userId] attribute to the state in the reducer. However, before doing this, you must first initialize the property with an empty object and then assign it { cart:[] }. See the Example in the documentation, where there is a paragraph that says: Immer does not automatically create nested objects or arrays for you - you must create them yourself.

    reply
    0
  • Cancelreply