Skip to content

Instantly share code, notes, and snippets.

@jagdishlove
Last active December 19, 2021 18:25
Show Gist options
  • Save jagdishlove/2eb8e07d63f99688d012e5a18be786cd to your computer and use it in GitHub Desktop.
Save jagdishlove/2eb8e07d63f99688d012e5a18be786cd to your computer and use it in GitHub Desktop.
onPage reload useEffect with useQuery. for any component e.g Modal.

credit

I don't store return data from query to react state. I just feel like that's an anti-pattern. You should just use the returned data as it is like below:

const { loading, data, error } = useQuery(SOME_QUERY)

// If you absolutely need to cache the mutated data you can do the below. But
// most of the time you won't need to use useMemo at all.
const cachedMutatedData = useMemo(() =>{
  if (loading || error) return null

  // mutate data here
  return data
}, [loading, error, data])

if (loading) return <Loader />
if (error) return <Error />

// safe to assume data now exist and you can use data.
const mutatedData = (() =>{
  // if you want to mutate the data for some reason
  return data
})()

return <YourComponent data={mutatedData}  />

But if you must store the returned data, could do below:

const { loading, data, error } = useQuery(SOME_QUERY)
const [state, setState] = React.useState([])

React.useEffect(() =>{
  // do some checking here to ensure data exist
  if (data) {
    // mutate data if you need to
    setState(data)
  }
}, [data])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment