Subscribe & hooks not reacting when the slice is an array
See original GitHub issueI have a state which is basically:
type State = {
items: {
a: string,
b: number
}[]
}
Pushing another item to the items
array, or mutating the a
or b
props of an item won’t trigger an update if subscribed to only the items
slice, like:
useStore.subscribe(console.log x => x.items);
or
const items= useStore(x => x.items);
useEffect(() => {
console.log(items);
}, [items]);
Subscribing to the entire store (eg const state = useStore()
)works fine, but I’d like to only monitor this slice of state.
I’m using Immer middleware to update state, and an example action that adds an item is:
addItem: (item) => set((draft) => void draft.items.unshift(item);
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (3 by maintainers)
Top Results From Across the Web
React hooks updating array is not working - Stack Overflow
The issue is that every time your component renders, it executes both completeTask and deleteTask , because you are using function calls as ......
Read more >Nested field arrays break data.slice · Issue #1208 - GitHub
Go to https://codesandbox.io/s/react-hook-form-defaultvalues-4o5iu; Click on "Add element"; Click on "add subelement" twice; Click on "remove ...
Read more >React hooks - working with state (arrays) - DEV Community
To use the useState hook you will need to import it from React. ... state to the updatedUsers setUsers(updateUsers); // array.slice method ...
Read more >A Lesser-Known Trick with React Hook Dependencies
An unorthodox React Hook trick for declaring your dependency array. ... only be updated when the incoming array does not deeply equate to...
Read more >Array.prototype.slice() - JavaScript - MDN Web Docs
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I am an idiot who forgot to put in immer in the actual producer. 🤦♂️
That’s an antipattern in Immer. You can’t both mutate the state and return a new one. What I can do is use
draft.items = [...draft.items]
after every update which is kinda missing the point since I’d have to do it in every action.I’m not sure why Zustand detects the entire store update.