Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to reload data client-side #57

Open
guillaumewuip opened this issue Aug 4, 2021 · 0 comments
Open

Ability to reload data client-side #57

guillaumewuip opened this issue Aug 4, 2021 · 0 comments

Comments

@guillaumewuip
Copy link

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:

}, []) // [] 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant