Replies: 3 comments 20 replies
-
Can anyone help? |
Beta Was this translation helpful? Give feedback.
-
@vaharoni I believe that you should create a custom storage |
Beta Was this translation helpful? Give feedback.
-
Eventually I noticed Here's the code I ended up with. It's likely only suitable for small stores, as saving the state independently for each action could get old very quickly. import { createStore, useStore } from 'zustand'
import AsyncStorage from '@react-native-async-storage/async-storage'
interface DisplayNameState {
hydrated: boolean
displayName: string
actions: {
setDisplayName: (displayName: string) => Promise<void>
}
}
const STORAGE_ITEM = 'display-name-store';
const displayNameStore = createStore<DisplayNameState>()(
(set, get) => ({
hydrated: false,
displayName: '',
actions: {
// This being async allows us to await
setDisplayName: async (displayName) => {
set({ displayName });
// removing actions - they are not serialized and we don't want them to override our functions during hydration
const { actions, ...newState } = get();
await AsyncStorage.setItem(STORAGE_ITEM, JSON.stringify(newState));
}
}
})
)
export const useDisplayNameStore = (selector: (selector: DisplayNameState) => any) => {
const { getState, setState } = displayNameStore;
if (!getState().hydrated) {
AsyncStorage.getItem(STORAGE_ITEM)
.then(data => {
const object = data ? JSON.parse(data) : {}
const initialState = { ...object, hydrated: true }
setState(initialState)
})
}
return useStore(displayNameStore, selector)
} Usage: export default function MyComponent() {
const { setDisplayName } = useDisplayNameStore(state => state.actions)
const router = useRouter();
// ...
async function onSomeEvent() {
// await here guarantees it is saved to the store before navigating
await setDisplayName('test')
router.navigate('somewhere')
}
// ...
} |
Beta Was this translation helpful? Give feedback.
-
I'm using
AsyncStorage
and would like to use the Persist middleware. I have a React page where I'd like some user event to save the data to the store and navigate to another page when this completes. The guide discusses the recipe of usingonRehydrateStorage
to set a flag when the hydration process finishes. But I did not see a reference for awaiting for the set operation to complete. In this discussion, the OP callsawait set({ fish: get().fish + 1 })
inside thepersist
callback, but typescript does not agree that the persist'sset
function returns a promise, so I'm assuming such usage is incorrect.What's the best practice here? Does the API expose a way to await the set operation? Or do I need to implement a store action that calls
AsyncStorage.setItem
, using the middleware mostly for reading but not for setting? Or is the idea perhaps to assume it will eventually be consistent?Beta Was this translation helpful? Give feedback.
All reactions