I am learning Redux. I am kind of new so I dont want to develop a bad habit at the start which is why i am writing this.
The doc i am reading says that in the reducers we need to always set the state where we change it - in other words do the following:
const someReducer = (state=initState, {type, payload}) => {
switch(type) {
case 'CHANGE_VALUE_ONE' : {
state = {...state, valueOne: payload }
break
}
case 'CHANGE_VALUE_TWO' : {
state = {...state, valueTwo: payload }
break
}
default:
state = state
}
return state
}
My approach was creating a newState constant which is identical to the state we receive, make change to the dummy and return it - or in code:
const userReducer = (state= {name: null, age: null}, {type, payload}) => {
const newState = {...state}
switch(type) {
case 'CHANGE_VALUE_ONE' : {
newState.valueOne= payload
break
}
case 'CHANGE_VALUE_TWO' : {
newState.valueTwo= payload
break
}
}
return newState
}
I think the way i do it is cleaner - if i have a complicated state i can easily change what i need to change without mutating the original state.