I'm creating a pagination system.
The reducer part looks like this:
(state, payload)=> {
if (state.venues === null) {
state.venues = [];
}
state.venues.push.apply(state.venues, payload.data)
return {
...state,
isRequesting: false,
hasVenues: true,
venues: state.venues,
hasMessage: false
}
},
I iterate through state.venues
in component.
The problem is, for the first request, state.venues
is null so I should convert it to empty array to append payload to it.
But with this approach I think I mutate the state which is no allowed(recommend) in redux.
So how do can I achieve this without state mutation?
To create a new array of venues use the spread operator:
var newVenues = [
...state.venues,
'Tokyo'
];
You can use Object.assign to avoid mutating the state:
var newState = Object.assign({}, state, { venues: newVenues });
(I've left out the other parts of the state in your example for clarity).
you can replace push
with concat
concat is Array's pure function returns new array without mutating original values
(state, payload) => {
if (state.venues === null) {
state.venues = [];
}
const newVenues = state.venues.concat(payload.data)
return {
...state,
isRequesting: false,
hasVenues: true,
venues: newVenues,
hasMessage: false
}
}
BTW:
if you find yourself repeatedly using Object spread or Object.assign in every sub-reducer / nested state. you should consider using Immutable.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With