useQuery parameters that depends on previously query

I wonder how should I manage a useQuery hook (executed as soon as the component is mounted) that depends on a parameter that comes from a previous query.

For instance, I want to retrieve tasks given the current projectId in use. But the tasks page can be accessed even tho no projectId are available (hence en empty state is shown)

I don’t want to keep the projectId in global state but rather use the cached GET_PROJECT query to hydrate the GET_TASKS query.

Is it safe to query the cache before the useQuery hook and add a skip variable such as:

const Component = () => {
  const { projectId } client.readQuery({ query: GET_PROJECT })
  const { data, loading, error } = useQuery(
    GET_TASKS, {
      skip: !projectId,
      variables: { projectId }
    }
  )
  // ...
  return data
}

Hello! Yes, this method should work great, and it’s a nice example of using the skip option. :+1:

1 Like