0

I am completely new to zustand and I would love to know if it is possible to make changes to a store from inside of another one? If so, please finish modify increasePopulation function in a way that it increases animals in forestStore as well. Thanks

const bearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  //should also increase animals count in forestStore
}))

const forestStore = create((set) => ({
  animals: 0,
}))
Terlan
  • 13
  • 3
  • https://stackoverflow.com/questions/74046364/zustand-get-state-from-another-zustand-store Might be a duplicate – ETCasual Jul 20 '23 at 11:35

1 Answers1

0

const bearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => {
    // Get the current state of the forestStore
    const forestState = forestStore.getState();

    // Update the state of forestStore with increased animals count
    forestStore.setState({ animals: forestState.animals + 1 });

    // Update the bears count in bearStore
    set((state) => ({ bears: state.bears + 1 }));
  },
}));

const forestStore = create((set) => ({
  animals: 0,
}));

export { bearStore, forestStore };