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****.....
If 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.
The fundamental idea of the object spread operator is to create a new plain object using the own properties of an existing object. So {... obj} creates a new object with the same properties and values as obj . For plain old JavaScript objects, you're essentially creating a copy of obj .
Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list. There are three distinct places that accept the spread syntax: Function arguments list ( myFunction(a, ...iterableObj, b) )
If 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.
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