External api for async inital state #676
-
Hi! I want to try to use zustand for a project where the inital state is always fetched from an external api. const useStore = create(set => ({
// Fetch that gets the current bears from api
bears: await getBearsAsync(),
increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 })
})) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
The initial value has to be something in sync. const useStore = create(set => ({
bears: null,
increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 })
}))
// Fetch that gets the current bears from api
getBearsAsync().then((bears) => useStore.setState({ bears })) |
Beta Was this translation helpful? Give feedback.
-
I built a third-party library called leo-query that makes this easier. It handles gotchas with loading state, errors, caching, retries, stale data, etc. import {create} from "zustand";
import {query, hook} from "leo-query";
const useStore = create(set => ({
// Fetch that gets the current bears from api
bears: query(getBearsAsync),
increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 })
}));
const useStoreAsync = hook(useStore, /*suspense*/ false);
const YourComponent = () => {
const bears = useStoreAsync(s => s.bears);
if (bears.isLoading) {
return <div>Loading...</div>;
}
return <div>{bears.value}</div>;
}; |
Beta Was this translation helpful? Give feedback.
The initial value has to be something in sync.