pmndrs / zustand

🐻 Bear necessities for state management in React

Home Page:https://zustand-demo.pmnd.rs/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

State updated in one component but not in another one

Kirin28 opened this issue · comments

Hi, I ran into an issue with a state not being updated between the two components. The store.ts looks like this:
import { create } from 'zustand';

type State = { island_id: string }

type Action = { setIsland_id: (island_id: State['island_id']) => void }

export const useStore = create<State & Action>((set) => ({ island_id: '', setIsland_id: (island_id) => set(() => ({ island_id: island_id })), }));

Then, in one component, I set the value based on e.target.value:

const island_id = useStore((state) => state.island_id);

const setIsland_id = useStore((state) => state.setIsland_id);

const handleIslandChange = (e) => { setIsland_id(e.target.value); for (const [key, value] of Object.entries(islandIds)) { if (value === e.target.value) { setIslandThingId(+key); } } }

and in the return statement:

<Form.Select aria-label="Default select" id="select-island" onChange={handleIslandChange}>
<option value={islandIds[1]}>Sustainable Buildings Demo</option>
<option value={islandIds[4]}>North District</option>
<option value={islandIds[5]}>Southeast District</option>
</Form.Select>

The state in this component is indeed being updated (I can see the state changing in the console.log and react components tab, however, in the second component, which is supposed to reuse the island_id state from the first component , the value is an empty string (what I initially set in the store.ts) and it is not being updated no matter how many times I update the state in the first component. Here is the code in the 2nd component:

const island_id = useStore((state) => state.island_id);

React.useEffect(() => { console.log(island_id); }, [island_id]);

I'm fairly new to zustand and other global state management libraries so any help would be appreciated!