Simple reducer accumulator should not be mutating the state, why is it?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Simple reducer accumulator should not be mutating the state, why is it?



For some reason my reducer is only returning a single element in the categories collection.


categories



I'm just learning this accumlator logic, so I have kept it simple which I thought was suppose to simply return the exact same state as I started with.



My state in JSON looks like:



"account":
"id":7,
"categories":[

"id":7,
"products":[

"productId":54

]
,

"id":9,
"products":[

"productId":89

]

]




In my reducer I have the following:


return
...state,
account:
...state.account,
categories: [state.account.categories.reduce((acc, cat) =>
return ...acc, ...cat
, )]

;



When I output my state, I see that for some reason it has removed one of the categories from the collection.


categories



Why isn't my state the same since the accumulator isn't filtering anything? It should be the exact same as it started with.





you are spreading cat object in the return. should be ...acc, cat
– marzelin
4 mins ago


...acc, cat





also it's not the same state: you convert array into one object enclosed in an array
– marzelin
2 mins ago




1 Answer
1



if you want to return categories unchanged (but with a different reference), you should do it like this:


categories: state.account.categories.reduce((acc, cat) =>
return [...acc, cat];
, )






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS