Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React/Redux - Add object to start of array using spread operator

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****.....
like image 751
peter flanagan Avatar asked Feb 10 '17 13:02

peter flanagan


People also ask

How do you add an object to an array using the spread operator in react?

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.

How do you create a new object using the spread operator?

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 .

Can we use spread operator on array of object?

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) )


1 Answers

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.

like image 77
Jack Murdoch Avatar answered Sep 18 '22 00:09

Jack Murdoch