How to use UseQuery with useEffect?

Viewed 8906

How to use UseQuery in React.UseEffect? this is my simple query

  const {allrecord} = useQuery(ME, {
    onCompleted: ({ meTeacher}) => {
      setUser(meIAM);
      getRecords({
        variables: {
          orgId: meIAM.organization.id,
          pagingArg: {},
        },
      }).then(({ data }) => displayRecord(data.record));
    },
  });
  useEffect(() => {
    console.log(allLocations)
  }, []);
3 Answers

useQuery is a hook and as such cannot be used under a branch.

This means that you must call useQuery inside your component and not under a branch statement (if/else/switch/useEffect).

If you need to do something with the result of a useQuery just use a useEffect with a dependency on that results

The Apollo Client useQuery hook automatically executes the corresponding query when the component renders. This makes it very similar to executing a query in useEffect with no dependencies. Like:

useEffect(() => {
  const data = executeQuery()
}, [])

There's an alternative hook, useLazyQuery which can be used to execute a query in response to some event, like a button press.

Good answer here https://github.com/trojanowski/react-apollo-hooks/issues/158

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}  />
Related