user2235768
user2235768

Reputation: 323

How to set multiple object values when using Immutable JS map

I am new to redux, Is this correct way of doing redux in following code, please? This is a reducer method when action called to execute currentTime.

import { combineReducers } from 'redux';
import { UPDATE_TIME } from './actions';
import { Map } from 'immutable';

 const initialState = Map({update:false, currentTime: ""});

 function currentTime(state = initialState, action) {
  switch (action.type) {
    case UPDATE_TIME:
      return {...state, update: true, currentTime: action.time };
    default:
      return state;
  }
} 

const currentTimeReducer = combineReducers({
    currentTime
});

export default currentTimeReducer

Upvotes: 0

Views: 3304

Answers (2)

Narasimha Reddy - Geeker
Narasimha Reddy - Geeker

Reputation: 3860

We use immutable JS to create new instance on each small change in the existing object. Immutable JS MAP has a set method to set attribute and return new instance of the object. Here you can find api doc for MAP

import { combineReducers } from 'redux';
    import { UPDATE_TIME } from './actions';
    import { Map } from 'immutable';

     const initialState = Map({update:false, currentTime: ""});

     function currentTime(state = initialState, action) {
      switch (action.type) {
        case UPDATE_TIME:
            let newState = state;
            newState = newState.set('update', true );
            newState = newState.set('currentTime', action.time);
            return newState;
        default:
          return state;
      }
    } 

    const currentTimeReducer = combineReducers({
        currentTime
    });

    export default currentTimeReducer

Look best practices in this doc

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281716

There are multiple ways to do it

  1. You can set the value using set() function

      case UPDATE_TIME:
         state = state.set('update', true);
         return state.set('currentTime', action.time);
    

    or even

     case UPDATE_TIME:
         return state.set('update', true)
                     .set('currentTime', action.time);
    

However this is not feasible when you have multiple changes

  1. The other option is merge()

    case UPDATE_TIME:
       return state.merge({update: true, currentTime: action.time})
    

However in case of a nested state update you would need to do a deepMerge. See the details of mergeDeep

Upvotes: 7

Related Questions