react-frontload
react-frontload copied to clipboard
Ability to reload data client-side
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: https://github.com/davnicwil/react-frontload/blob/a2063644e23dfee559fee47dd88575872a773e7b/src/index.tsx#L474
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!