Using async code in a reducer #258
Replies: 2 comments
-
|
@erictompkins within the normal store reducers? No, those are sync-only. But you shouldn't need to handle this at the store reducer level. This hook has several features that don't perfectly align with stuff Zedux has out of the box. And that's fine - they can all go in a custom injector. Copying the whole hook into an If you don't mind some (honestly minor) React version lock-in, you could even avoid copying the hook by replacing React's dispatcher and using the hook directly in an injector like this: const injectSimpleReducer: typeof useSimpleReducer = (...args) => {
// assuming React v19, the internals look like this:
const internals =
React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE ??
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE
if (!internals) {
throw new Error(
'React internals not found. This injector must be updated for React versions besides v19'
)
}
const prevDispatcher = internals.H
// replace React's dispatcher, supplanting the hooks that we know `useSimpleReducer` uses with Zedux injectors.
internals.H = {
useCallback: injectCallback,
useRef: injectRef,
useEffect: injectEffect,
useState: <T,>(stateOrFactory: T | (() => T)) => {
const signal = injectSignal(stateOrFactory) // assuming Zedux v2
return [signal.get(), (value: T) => signal.set(value)]
},
}
const result = useSimpleReducer(...args)
internals.H = prevDispatcher // restore the previous dispatcher
return result
}
// then use in an atom like so:
const exampleAtom = atom('example', () => {
const [count, actions, queue, error] = injectSimpleReducer(0, {
increment: async state => state + 1,
decrement: async state => state - 1,
})
})This is obviously frowned upon in React but meh, Zedux makes it easy and it works and is pretty clear about being tied to a specific React version. |
Beta Was this translation helpful? Give feedback.
-
|
Thank you @bowheart. We ended up removing the need for async, and we are now just trying to get the Reducer to work. The documentation is helpful, but we're missing a few things. I started a separate discussion on how to use the reducer. #259 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Is it possible to have asynchronous code within a Zedux reducer?
We are currently using a custom hook (https://www.npmjs.com/package/@bitovi/use-simple-reducer) to do this but wanted to know if this is something that can be done with Zedux.
In some actions, we are awaiting another hook that returns a promise.
Below is how we are currently doing it (note - not all the code is included here, but hopefully enough to get the idea)
Beta Was this translation helpful? Give feedback.
All reactions