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 { bineReducers } 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 = bineReducers({
currentTime
});
export default currentTimeReducer
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 { bineReducers } 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 = bineReducers({
currentTime
});
export default currentTimeReducer
Share
Improve this question
edited Sep 4, 2017 at 11:26
Shubham Khatri
282k58 gold badges431 silver badges411 bronze badges
asked Sep 4, 2017 at 10:57
user2235768user2235768
3231 gold badge5 silver badges18 bronze badges
2 Answers
Reset to default 7There are multiple ways to do it
You can set the value using
set()
functioncase 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
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
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 { bineReducers } 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 = bineReducers({
currentTime
});
export default currentTimeReducer
Look best practices in this doc