Question: Async Actions
shyam-habarakada opened this issue · comments
First, thanks for putting this library out. It gets me most of what I was trying to put together myself while looking into adopting the new hooks features.
How would I use it implementing actions that update the state asynchronously (e.g. https://redux.js.org/advanced/async-actions)?
Hello @shyam-habarakada. Thanks for showing interest on this simple project.
This is how I would do it: I would create an intermediate hook that take care of actions, including async ones. and since react-hookstore has no opinion on actions, they can be async out of the box, no middlewares required. Let me examplify:
import { createStore, useStore } from 'react-hookstore';
import { fetchData } from './api';
function myStoreReducer(state, action) {
/* your reducer logic here */
}
const myStore = createStore('myStore', { data: [] }, myStoreReducer);
const actions = {
async getData(params) {
const data = await fetchData(params);
myStore.dispatch({ action: 'GET_DATA', payload: data })
},
/* additional actions here */
}
export default function useMyStore() {
const [ state ] = useStore(myStore);
return {
state,
actions
}
}
Since actions can be defined the way you want, other implementations would also work, but I like this one.
Let me know if this works for you and feel free to ask anything else!
yes but, Hooks can only be called inside the body of a function component.
So here, from your example, something will scream ( const [state,actions] = useDataStore(); )
Would be nice to be able to override that React thing, calling dispatch from the store declarative file
Or maybe do i something wrong
@Mydde The actions
object uses the store.dispatch
method that can be called outside components (it is not a hook), I believe this is exactly what you want. Is that correct?
If you want to dispatch actions outside this file, then ok, we have a problem. I would export the actions variable as well, and it would work fine. (and you can get fancier and export a store wrapper together with the actions if you want)
Yes, that's correct, Error message "Hooks can only be called inside the body of a function component" was a react@alpha bug. gone, all is ok
Does calling actions.getData() init a component re-render ? i would like to trigger it from useEffect() but when doing so i've got a loop
It trigger a re-render, but that's fine. It can be used inside useEffect(). you're probably just not declaring useEffect to be triggered only on mount, may it be the case?
// loops like crazy
useEffect(actions.getData)
// only activates on mount, the empty array declares no dependency on updates,
// so only mount will execute the callback
useEffect(actions.getData, [])
that's fine, i'm going back to the docs
Cool. I'll close this issue now as the original and subsequent related questions were answered