-
Notifications
You must be signed in to change notification settings - Fork 20
Description
Hello and thanks for this powerful react-frontload library!
I'm wondering how I can implement reload client-side.
My use case is the following. I have one high level hook that retrieves data (SSR and client-side) with useFrontload. I would like the hook to provide a reload function for the UI to be able to refresh data when the user click on something.
function myHook() {
const { data } = useFrontload('my-component', async ({ api }) => {
const stuff = await api.getStuff();
return stuff
})
return {
data,
reload, // how to implement this reload function that will fetch data again client-side?
}
}As far as I understand this is not currently possible because the useEffet inside useFrontload only run once, on mount:
Line 474 in a206364
| }, []) // [] to only run once on mount |
Am I missing something?
Would you accept a PR that exposes a reload function from useFrontload result? This function would internally increment a useState counter used as a dependency for the useEffect, forcing it to run again.
const [forcedReload, setForcedReload] = React.useState<number>(0)
React.useEffect(() => {
// current use effect
}, [forcedReload])
return {
...state,
setData: (fn: (data: T) => T) => {
setState((state) => ({
...state,
data: fn(state.data),
}))
},
reload: () => { // adding this
setForcedReload(state => state +1)
}
} Let me know if it looks good for you :) Thanks!