I am using a redux reducer to add objects to a state array. This is working correctly, however, the objects are being added to the end of the array. I have searched high and low, but cannot figure out how to use this syntax, not mutate the array and add the object to the start of an array.
export default (state = [], action) => {
switch(action.type) {
case 'MOVIE_ADDED_TO_WATCHLIST':
return [
...state,
action.movie
];
}
...****rest of the reducer here****.....
I am using a redux reducer to add objects to a state array. This is working correctly, however, the objects are being added to the end of the array. I have searched high and low, but cannot figure out how to use this syntax, not mutate the array and add the object to the start of an array.
export default (state = [], action) => {
switch(action.type) {
case 'MOVIE_ADDED_TO_WATCHLIST':
return [
...state,
action.movie
];
}
...****rest of the reducer here****.....
Share
Improve this question
asked Feb 10, 2017 at 13:19
peter flanaganpeter flanagan
9,79027 gold badges81 silver badges138 bronze badges
1 Answer
Reset to default 19If you want to use the spread operator to add items to the beginning of an array, just use the spread operator after the new values. For example:
let a = [1, 2, 3, 4, 5];
let b = [0, ...a];
console.log(a);
console.log(b);
Additionally, you can also use .concat
:
var a = [1, 2, 3, 4, 5];
var b = [0].concat(a);
console.log(a);
console.log(b);
You can see a working example of this here.