So I'm building an application in redux and I ran into the problem outlined in the redux documentation where my view would not update after an action was dispatched. The documentation suggests that this happens when you mutate the state. The only problem is, I don't understand how what I was doing is considered a mutation:
case AppConstants.UPDATE_ALL_TIMERS:
return action.timers
This, however, does work:
case AppConstants.UPDATE_ALL_TIMERS:
let newState = state.map((timer, index) => {
return action.timers[index]
});
return newState
How is it that just returning the value of the action as your new state is considered mutating the state? What am I missing?
Below is the entirety of my reducer, the two cases prior to UPDATE_ALL_TIMERS worked just fine. The reducer is being used with combine reducers and is only receiving the timers slice of state, which is an array of objects.
export default function(state = initialState, action) {
switch(action.type) {
case AppConstants.ADD_TIMER:
let newState = [...state, action.timer];
return newState
case AppConstants.UPDATE_TIMER:
newState = state.map((timer, index) => {
if(index == action.timerID) {
const updatedTimer = {
...timer,
elapsed: action.elapsed
}
return updatedTimer
}
return timer
});
return newState
case AppConstants.UPDATE_ALL_TIMERS:
newState = state.map((timer, index) => {
return action.timers[index]
});
return newState
default:
return state
}
}
Can you post your component ?
Usually when the Store state is alright and well updated yet the component do not re render it's because of deep nested mapped properties.
react-redux do not do deep checks to verify if a value has changed on deep nested mapped objects
Related
My initial version did not use cloning. However useSelector() was not firing until I added another clone statement.
I thought that by cloning the containing object on a state change this would cause it tor fire. Particularly this line here.
let newState = { ...state };
That is a sub question. Why does not returning a new state cause useSelector to fire.
I had to add a second clone to get it to fire as follows:
const clone = [...newState.messages];
I find this behavior odd, and wonder if it might be a bug. Also not very efficient to have to clone my messages array.
The complete reducer is as follows:
const Messages = (state = {messages: false}, action) => {
let newState = { ...state };
switch(action.type) {
case 'initializeMessages':
newState.messages = action.messages;
return newState;
case 'addMessage':
// cloning is required to make useSelector() fire
const clone = [...newState.messages];
clone.unshift(action.message);
newState.messages = clone;
return newState;
}
return state;
};
and I use it as follows:
Updating
const messages = useSelector( (state) => state.Messages.messages );
Dispatching
dispatch({type: 'addMessage', message: message});
UPDATE
After updating to hooks, my reduces don't work anymore unless I clone embedded arrays. Before I did not have to do this:
you are right, you need to do the same for addMessage block like:
const newState = {
...state,
messages: [
...newState.messages,
action.message
]
};
Lets imagine a simple reducer:
const [state, setState] = React.useReducer(myReducer, {})
And myReducer with one single case (simplified version):
const myReducer = (state, action) => {
switch (action.type) {
case 'UPDATE_STATE': {
// Code to update here...
}
}
}
Now, which of the following statements is best suited to update a state - and why:
NOTE: payload = state.
METHOD 1
case 'UPDATE_STATE': {
const updatedState = action.payload
updatedState.object = true
return updatedState
}
METHOD 2
case 'UPDATE_STATE': {
const updatedState = action.payload
updatedState.object= true
return { ...state, updatedState }
}
METHOD 3
case 'UPDATE_STATE': {
const updatedState = action.payload
updatedState.object= true
return { ...state, ...updatedState }
}
METHOD 4
case 'UPDATE_STATE': {
return ({ ...state, object: true })
}
I think you should Use method 4. You are not mutating the state here, which is the React way.
case 'UPDATE_STATE': {
return ({ ...state, object: true })
}
Note: Spread operator ... creates different references up to one level only.
EDIT: Based on comments, here is a simple example of how you could be mutating state, even with the simplest of objects if you are not using ....
let state = { object : true};
let payload = state;
state.object = false;
console.log(state);
console.log(payload);
Even with ... you might have deeply nested objects. They will have the same problem, unless you want to spread at every level. There are libraries to help you with deep objets like immutable.js.
I've noticed that in many useReducer examples, the spread operator is used in the reducer like this:
const reducer = (state, action) => {
switch (action.type) {
case 'increment1':
return { ...state, count1: state.count1 + 1 };
case 'decrement1':
return { ...state, count1: state.count1 - 1 };
case 'increment2':
return { ...state, count2: state.count2 + 1 };
case 'decrement2':
return { ...state, count2: state.count2 - 1 };
default:
throw new Error('Unexpected action');
}
};
However in many of my practices, I removed ...state and had no issues at all. I understand that ...state is used to preserve the state of the remaining states, but would a reducer preserve those states already so the ...state is not needed?
Can someone give me some examples where ...state is a must and causes issues when removed with useReducer hook? Thanks in advance!
No, a reducer function alone would not preserve existing state, you should always be in the habit shallow copy existing state. It will help you avoid a class of state update bugs.
A single example I can think of when spreading the existing state may not be necessary is in the case where it isn't an object.
Ex: a "count" state
const reducer = (state = 0, action) => {
// logic to increment/decrement/reset state
};
Ex: a single "status" state
const reducer = (state = "LOADING", action) => {
// logic to update status state
};
Spreading the existing state is a must for any state object with multiple properties since a new state object is returned each time, in order to preserve all the existing state properties that are not being updated.
Edit 1
Can you give an example when NO shallow copying causing state update bugs?
const initialState = {
data: [],
loading: false,
};
const reducer = (state, action) => {
switch(action.type) {
case LOAD_DATA:
return {
...state,
loading: true,
};
case LOAD_DATA_SUCCESS:
return {
...state,
data: action.data,
loading: false
};
case LOAD_DATA_FAILURE:
return {
loading: false,
error: action.error,
};
default:
return state;
}
};
As can been seen in this example, upon a data load failure the reducer neglects to copy the existing state into the new state object.
const [state, dispatch] = useReducer(reducer, initialState);
...
useEffect(() => {
dispatch({ type: LOAD_DATA });
// logic to fetch and have loading failure
}, []);
return (
<>
...
{state.data.map(...) // <-- throws error state.data undefined after failure
...
</>
);
Any selector or UI logic that assumes state.data always exists or is always an array will fail with error. The initial render will work since state.data is an empty array and can be mapped, but upon a loading error state.data is removed from state.
From a Redux tutorial I've been going through they allow you to add a place multiple times. I changed the reducer to reject duplicates. My question is, (see code), do I have to return the state if no updates are made or is there some other way of indicating no state is changed?
function placeReducer(state = initialState, action) {
switch (action.type) {
case ADD_PLACE:
const existing = state.places.find((item) => item.value == action.payload);
if (existing) {
return {...state};
}
return {
...state,
places: state.places.concat({
key: Math.random(),
value: action.payload
})
};
default:
return state;
}
}
Just return the state, no need to create a new copy.
Cannot work out what is going on here but basically i have a json file which has a load of products. im trying to then render the ones I want
here is my reducer:
export default(state = initialState, action) => {
switch(action.type){
case Types.SHOW_PRODUCTS: {
console.log('here1');
let productsToShow = data.filter(category => category.link === action.category)
const newState = [].concat(productsToShow[0].products)
return newState;
}
default:
console.log('here2');
return state;
}
}
when I log the state in my store, it says that productsToRender is an array of length 5 (this is correct)
however, when I log (this.props) in one of my components, it says that the length is 0
in the above reducer, the console.log('here 1') is the last console log being called, meaning that it is definitely returning products ( that is verified in the store state). so im not sure why it is then wiping it in that component?
in that component I call this
componentWillMount = () => {
this.props.showProducts(this.props.chosenCategory.category)
}
which passes in the chosen category so I now what products to render
however, logging this.props in the render method below, is showing it to be an empty array
of course I can post more code if necessary but any reason for this funky behaviour?
extra info:
interestingly when I do this:
default:
console.log('here2');
return [{name: 'prod'}];
}
and then log this.props, it now contains this array with this object???
The store should be immutable, that is, the value you return should be made immutable.
I assume you are adding only a single array in the store
Try changing the reducer like,
const initialState = [];
export default(state = initialState, action) => {
switch(action.type){
case Types.SHOW_PRODUCTS: {
console.log('here1');
let productsToShow = data.filter(category => category.link === action.category)
let newState = [...state,...productsToShow[0].products]
return newState;
}
default:
console.log('here2');
return state;
}
}