Mizlul
Mizlul

Reputation: 2290

Why we use spread operator into redux

I have seen the following code:

export default function productReducer(state = initialState, action) {
    switch(action.type) {
        case FETCH_PRODUCTS_BEGIN:
            return {
                ...state,
                loading: true,
                error: null
            };

        case FETCH_PRODUCTS_SUCCESS:
            return {
                ...state,
                loading: false,
                items: action.payload.products
            };

        case FETCH_PRODUCTS_FAILURE:
            return {
                ...state,
                loading: false,
                error: action.payload.error,
                items: []
            };

        default:
            return state;
    }
}

But don't understand why do we use ...state every time for each case.

Can't we just write:

return {
                    loading: false,
                    error: action.payload.error,
                    items: action.payload.products
                };

Anyone can explain this?

Upvotes: 0

Views: 70

Answers (2)

Pipe
Pipe

Reputation: 2424

Because commonly you want to keep other keys inside your state...

If your state has:

{
   items:['a', 'b', 'c'],
   loading: false,
   error: null
}

and you only return for example:

case FETCH_PRODUCTS_BEGIN:
    return {
        // ...state, --> Without this line
        loading: true,
        error: null
    };

Your new state will be

{
    loading: true,
    error: null
}

And your items will be lost.

Then, returning:

case FETCH_PRODUCTS_BEGIN:
    return {
        ...state,
        loading: true,
        error: null
    };

You are saying

Return a copy of state, but overriding loading and error keys"

Upvotes: 4

Yaroslav Bigus
Yaroslav Bigus

Reputation: 678

This is for creating new copied state object with new or updated values (without this you would need manually specify every state field).

Object.assign can be used as alternative

Redux Docs has really good explanation about using spread operator.

Upvotes: 1

Related Questions