Zustand get state from another Zustand store
Asked Answered
P

3

10

*I have created 2 Zustand stores in react application, one is called UserStore, and the other is called SettingsStore, how can I get the state from UserStore to SettingsStore? *

import create from 'zustand';

const UserStore = (set, get) => ({

user: {},

});

I want to use this "user" variable to my other store called SettingsStore

import create from 'zustand';

const SettingsStore = (set, get) => ({



});
Portsmouth answered 12/10, 2022 at 18:17 Comment(0)
C
26

You must import UserStore in SettingStore file, and then use UserStore.getState().user

Cellarage answered 13/10, 2022 at 8:1 Comment(0)
S
12

You can import the store within the other store and retrieve the state via the .getState() function.

import create from "zustand";

const useUserState = create((set, get) => ({
  userId: undefined,
}));

const useSettingState = create((set, get) => ({
  updateSetting: (user) => {
    const userId = useUserState.getState().userId;
    // do something with userId
  },
}));

Surcease answered 27/1, 2023 at 17:32 Comment(1)
Quite cool feature, this way you can import store methods from separate files too. At first could not find it in the official docs,I managed to find it only after I had seen it here, thanks.Pember
C
1

You can create custom hook

const useCustomHook = () => {
   const [userId ] = useUserStore(state => [state.userId]);
   const [ updateSetting ] = useSettingStore(state => [state.updateSetting])
      
       useEffect(() => {
       ///// yo can use useeffect otherwisw
       },[]);
    
       const result = updateSetting(user,userId)
    
       
       return result;
    
    
     }
    
    export { useCustomHook, ...}
Corinecorinna answered 13/2, 2023 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.