-
New Zustand user here! I am trying to update my store from outside of React. I suspect the state does get updated (although I can't actually tell), but my React component does not re-render. Basically, I want to update my animal store every time the animals in my AnimalManager change. So that my React component re-renders with the new animals. State: import create from 'zustand';
import {animalManager} from './AnimalManager';
export const useAnimalStore = create(() => ({
animals: animalManager.animals,
})); Manager: import { useAnimalStore } from "./AnimalStore";
class AnimalManager {
public animals = [
{
id: 1,
clicked: false,
},
{
id: 2,
clicked: false,
},
]
public markAnimalAsClicked = (animalId: string) => {
// Set the animal to clicked
const animalObj = this.animals.find(animal => animal.id == animalId);
animalObj.clicked = true;
// This does appear to update the state,
// but it does not cause a re-render
// of the animal component :(
useAnimalsStore.setState({ animals: this.animals })
}
} React component: import { useAnimalStore } from "./AnimalStore";
export const AnimalsComponent = () => {
// Get the animals from the store
const animals = useAnimalStore((state: any) => state.animals)
// When an animal button is clicked
const animalClicked = (animal) => {
animalManager.markAnimalAsClicked(animal.id);
}
// Render
return (
animals.map(animal => (
<button
key={animal.id}
onClick={() => animalClicked(animal)}
>
{animal.id}
</button>
))
)
} PS: The idea here is to be able to update my state from the Manager and have the Rect component update. I have also tried the vanilla store approach and then using that with the useState hook, but couldn't get that to work either. Please can I get some help getting this solved? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 8 replies
-
Zustand is built on immutability (as well as React). You can't mutate your state. useAnimalsStore.setState((state) => ({
animals: state.animals.filter((animal) => animal.id === animalId ? { ...animal, clicked: true } : animal)
})) |
Beta Was this translation helpful? Give feedback.
-
@dai-shi Still the zustand not forcing rerendering if is using immutability or not, simple child-parent relation, where child dispatching action, changing the state, and parent without props, the parent stays as it is, and react not rerendering it, no console.log statement u can see. Switching from contexes to zustand is overkill. |
Beta Was this translation helpful? Give feedback.
-
Well, to force a re-render, use the full store in the component (overkill, but works) export const AnimalsComponent = () => {
// Get the animals from the store
const animalStore = useAnimalStore();
const { animals } = animalStore
...
} |
Beta Was this translation helpful? Give feedback.
Zustand is built on immutability (as well as React). You can't mutate your state.