Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute query on every click using useLazyQuery()

Using useLazyQuery() hooks from @apollo/react-hooks I was able to execute a query on click of a button. But I cannot use it execute same query on consecutive clicks.

export default ({ queryVariables }) => {
  const [sendQuery, { data, loading }] = useLazyQuery(GET_DIRECTION, {
    variables: queryVariables
  });

  return <div onClick={sendQuery}>Click here</div>;
}

In the above the sendQuery executes only once.

like image 634
arjun Avatar asked Oct 07 '19 06:10

arjun


1 Answers

useLazyQuery uses the default network policy that of cache-first So I supposed your onClick function actually executes but because the returned value is what was in the cache, React notices no change in data as such the state is not updated since the returned data is what it already has that way no re-render and thing seem not to have changed. I suggest you should pass in a different network policy something like

  const [sendQuery, { data, loading }] = useLazyQuery(GET_DIRECTION, {
    variables: queryVariables,
    fetchPolicy: "network-only"
  });

This will mean you want the most recent information from your api hence basically no caching. You might also want to experiment on other option and see which one best suits you like cache-and-network: you can find out a little more here understanding-apollo-fetch-policies

like image 56
harisu Avatar answered Oct 26 '22 13:10

harisu