zustand: Mocking state broken in 4.2.0 (with AsyncStorage in React Native)
Summary
Hello and thank you for a great state library!
When upgrading to 4.2.0 and using persist, the suggested mock approach throws error TypeError: Cannot read properties of undefined (reading 'getItem')
Suggested mock code that breaks:
// when creating a store, we get its initial state, create a reset function and add it in the set
const create =
() =>
<S>(createState: StateCreator<S>) => {
const store = actualCreate<S>(createState); // <-- breaks here
const initialState = store.getState();
storeResetFns.add(() => store.setState(initialState, true));
return store;
};
Our persist setup:
import create from 'zustand';
import {createJSONStorage, persist} from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
...
const useAppState = create<State & Actions>()(
persist(
set => ({
...initialState,
setIsColdStarted: isColdStarted => set({isColdStarted}),
setSettings: settings =>
set(state => ({settings: {...state.settings, ...settings}})),
reset: () => set(initialState),
}),
{
name: 'appState',
storage: createJSONStorage(() => AsyncStorage), // <-- instead of deprecated getStorage: () => AsyncStorage
partialize: ({settings}) => ({
settings,
}),
},
),
);
About this issue
- Original URL
- State: closed
- Created a year ago
- Reactions: 2
- Comments: 35 (13 by maintainers)
Yes! Thanks for the effort!
hmm, sorry I thought it’s clear from my comment that it’s not in mocking, but in actual app that its causing problem. I just thought maybe this issue and mine have the same root cause but I guess a new issue might be better for it edit: I see I have to open discussion before openning an issue, doing that 😉 edit2: https://github.com/pmndrs/zustand/discussions/1516
@meypod Is your issue only with mocking? If it’s an issue for non-mocking context, you might want to open a new discussion?
Thanks for chiming in anyway. It might be a hint for someone.