Updating state doesn't trigger a component rerender
See original GitHub issue👋 So I have set up a simple store, keeping track of an array of objects, and I have one action that edits just one of those objects based on an ID parameter.
// Format of the list of objects
list: [
{
id: '123',
// other data
},
// other objects
],
editItem: (id, newItem) => set(state => {
return {
list: state.list.map(item => {
if (item.id == id) {
return newItem;
}
return item;
}),
};
}),
// more actions
I have a component that is using this list
, which reflects the data in just one of the objects, and so I’m using the following code to get that inside my component function:
// 'id' is passed through my navigation
const items = useStore(state => state.list);
const item = items.find(i => i.id == id);
I’m displaying a property from my item
in that component, but my problem occurs when I call that editItem
action from another screen, my original component doesn’t rerender. I’m sure that Zustand is updating the state correctly, because a subscribe
listener on my items
array gets called every time it updates.
Any help would be very appreciated; not sure if I’m just missing something or if this is an issue with Zustand.
Issue Analytics
- State:
- Created 3 years ago
- Comments:8 (5 by maintainers)
Top GitHub Comments
@onygami You need to update state immutably. Here’s the fix: https://codesandbox.io/s/inspiring-mountain-z93fi?file=/src/useTodos.ts
@dai-shi Thanks, that was dumb of me, I thought a simple return will update state immutably.