8

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****.....

1 Answer 1

19

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.