Skip to content

Instantly share code, notes, and snippets.

@vincicat
Last active January 14, 2020 03:08
Show Gist options
  • Save vincicat/4a266465cc4e3adc234b7b7a63f675a2 to your computer and use it in GitHub Desktop.
Save vincicat/4a266465cc4e3adc234b7b7a63f675a2 to your computer and use it in GitHub Desktop.
Apollo client notes

Rendering Cycle

Every useQuery() will cause 3 renderings after mount:

  1. with cache-data (StatusCode 1)
  2. "now loading" (StatusCode 1)
  3. with data-result, or error (StatusCode 7)

If you need some prefetching, consider using useLazyQuery()

Cache

Tricky beast.

Hidden Rule:

  • Every thing inside Query must have a type, include your data feed
  • limited ability: querying Cache can return single item or ALL items

Known issues

  • networkStatus isn't work #195,#2926
  • Suspend isn't not work for hooks #88

bulletproof result capture

Note:

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 (loading) return <Loader />
if (error) return <Error />

// safe to assume data now exist and you can use data.
const mutatedData = React.useMemo(() => {
  // if you want to mutate the data for some reason
  return data
}, [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