redux Reducer Using Immutable

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Immutable is a great library that provides us with immutable versions of widely used types of collections, such as Lists, Stacks, Maps, and more.

It simplifies the manipulation of the state and makes it easier to make pure calculations and avoid mutation.

Let's see how the Basic reducer can be rewritten using Immutable's Map and List structures:

import { ACTION_ERROR, ACTION_ENTITIES_LOADED, ACTION_ENTITY_CREATED } from './actions';

// Import Immutable
import Immutable from 'immutable';


// Set up a default state using a Map, a structure very similar to objects
// Note that states in Redux can be anything, not just objects
const initialState = Immutable.Map({
    error: undefined,
    entities: Immutable.List()
});

export default (state = initialState, action) => {

    switch(action.type) {

        case ACTION_ERROR:
            return state.set('error', action.error);

        case ACTION_ENTITIES_LOADED:
            return state.merge({
                entities: Immutable.List(action.entities)
                error: undefined
            });
        
        case ACTION_ENTITY_CREATED:
            return state.set('entities', state.entities.push(action.entity));

        default:
            return state;
    }
};

As you may have seen, handling the immutable state gets easier using Immutable.



Got any redux Question?