Best way to integrate custom hook into store #1308
-
I am integrating a sub-app that uses Zustand into a larger app. To integrate the sub-app I need to use custom hooks from the parent app (mainly custom fetch hooks that handle auth) within the actions of the store of the sub-app. What is the best way to do this? Expanding on the basic async example from the docs: Custom fetch hook from parent app:
Store using custom hook in the store:
So where/how can I use the custom hook |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Store definition is pure JS. You want to create a new hook from the store hook. const useCustomFetch = (path) => { ... }
const useFishStore = create((set) => ({
fishies: {},
setFishes: (fishes) => set({ fishes }),
}))
const useFishFetch = () => {
const customFetch = useCustomFetch()
const setFishes = useFishStore((state) => state.setFishes)
return async (pond) => {
const response = await customFetch(pond)
set({ fishies: await response.json() })
}
} You can feed customFetch into the store action. const useCustomFetch = (path) => { ... }
const useFishStore = create((set) => ({
fishies: {},
fetch: async (pond, customFetch) => {
const response = await customFetch(pond)
set({ fishies: await response.json() })
},
}))
const useFishFetch = () => {
const customFetch = useCustomFetch()
return (pond) => useFishStore.getState().fetch(pond, customFetch)
} The thing is, store is global, while customFetch is contextual. |
Beta Was this translation helpful? Give feedback.
-
Just had the same question, so glad it has been answered! |
Beta Was this translation helpful? Give feedback.
-
To use TypeScript, you can utilize three separate files._First Create FolderName inside you can create index.ts file
Here is the ACTION FILE `
` |
Beta Was this translation helpful? Give feedback.
Store definition is pure JS. You want to create a new hook from the store hook.
You can feed customFetch into the store action.