Reputation: 5389
I am learning to write reducers for arrays. For example, one of the reducers changes array elements from integers to arrays.
[0, 3, 5, 3, 9, 8]
case ADD_NEST:
return state.map(i => [i, action.payload]);
[[0, 0], [3, 0], [5, 0], [3, 0], [9, 0], [8, 0]]
I'm trying to write a reducer that would change the second element of sub-arrays based on the condition of the first one. (eg, if the first element of the subarray is greater than 3
, change the second element to 1
).
[[0, 0], [3, 0], [5, 1], [3, 0], [9, 1], [8, 1]]
so far I have (not much as I'm stuck):
case SET_BIT:
return state.map(i => (i[0] > 3 ? ??? : i));
Thank you for advice!
Upvotes: 0
Views: 107
Reputation: 13071
Like this?
case SET_BIT:
return state.map(i => (i[0] > 3 ? [i[0], i[1] + 1] : i));
Although, that's a bit weird/dangerous. What happens if SET_BIT
gets dispatched when your state of that reducer is still a flat array? Then the above code will crash. Then you would have to do something like:
case SET_BIT:
return state.map(i => (
Array.isArray(i) && i[0] > 3
? [i[0], i[1] + 1]
: i
));
I don't know the details of what you are trying to do here, but generally speaking I think it's best to keep the structure of the state of a reducer consistent. I tend to avoid nested structures in the state of my redux store because I try to keep the state of my redux store as normalized as I can. That makes reducers a lot easier to maintain. If I need to nest stuff for my views I usually do that in the selectors.
But again, I lack context, so not sure if any of this advice is relevant to you. :-)
Upvotes: 1