0

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

2 Answers 2

7

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

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

3 Comments

Thanks for your detailed answer, is there any chance could do it by reselect on state?
What do you mean by reselect on state
From what I understand, reselect is for having memoizable selectors,I am not sure, if it will be used to update the Immutable states in redux store
0

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

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.