I came across some weird behavior that I would feel safer to understand
Below is the code of my reducer. I can not get why, but with this code the component tied to the redux state does not re-render. I can tell with the developper tools that the state is properly updated.
const initialState = {
allItems: [],
favItems: [],
}
export default (state = initialState, action) => {
let allItems
case CREATE_ITEM:
allItems = state.allItems
allItems.unshift(action.item)
return {
...state,
allItems: allItems,
}
}
Comparing with other actions in my reducer, I finally guess that there was something about the time cost of the operation, some other operations a bit more complicated seemed to work better...
So I added a timer
case CREATE_ITEM:
allItems = state.allItems
allItems.unshift(action.item)
setTimeout(() => {
return {
...state,
allItems: allItems,
}
}, 0)
And boom, it worked !
I really don't like this highly hacky solution.
Does anyone has any idea about what is happening and how I could solve this in a better way.
Notes :
- I'm working on react-native, but it doesn't seem related
- In the component, the redux state is selected with the
useSelector
hook
const items = useSelector((state) => state.items.allItems)