The method of defining dynamic keys is in redux's initialState
P粉478835592
2023-09-05 14:15:53
<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>
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.