user9240010
user9240010

Reputation:

Redux return a fresh object composed out of our existing state

I am trying to learn redux and stumbled upon this article from hackernoon

Everything was going great until I encountered this example

export default function reducer(state = {posts: []}, action) {
    switch (action.type) {
        case 'Add_USER_POST':
            return {
                ...state,
                posts: [
                    ...state.posts,
                    {
                        content: action.payload.content,
                    }
                ]
            };
        default:
            return state;
    }
}

For which the following explanation was given..

First, we added a default property posts to our default state and initialised it with [] . Next, we simply added a switch-case block that switches on action.type . Because our action had a type of Add_USER_POST it will be intercepted by the 1st case in our reducer’s switch-case and it will return a fresh object composed out of our existing state and add the newly added post to the posts array.

Here I am unable to understand the following lines (first and the last lines)

  1. First, we added a default property posts to our default state and initialised it with [] .

  2. return a fresh object composed out of our existing state and add the newly added post to the posts array

Can someone help me in understanding the above code in much more simpler terms?

[Update] got the first point, can someone explain me the working of part of code associated with second point

return {
                    ...state,
                    posts: [
                        ...state.posts,
                        {
                            content: action.payload.content,
                        }
                    ]
                };

Things I understood from the above code, We are returning an object which have our current state, then an array of posts which consists of things inside our state.posts and action.payload.content which we get from here

{
    type: 'Add_USER_POST',
    payload: {
        content: 'A quick brown fox jumped over the lazy dog',
    }
}

As in our article.

Upvotes: 2

Views: 91

Answers (1)

Fecosos
Fecosos

Reputation: 974

  1. This reducer function takes a state and an action parameters. If no parameters are passed to the reducer it simply returns an object containing an empty array of posts.

The default property :

state = {posts: []}

Sets a default object as the first parameter of the reducer function.

  1. The spread operator is being used to combine the previous state passed, the previous posts in that state's array and add a new post with the content passed in the action.payload.content.

DOCS

Default Parameters

Spread Operator

Upvotes: 2

Related Questions