How to execute query on every click using useLazyQuery()
Asked Answered
G

2

22

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.

Gris answered 7/10, 2019 at 6:27 Comment(0)
D
27

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

Diabolize answered 7/10, 2019 at 7:5 Comment(1)
call the onClick like this onClick={() => sendQuery()}Diabolize
E
3

As per the docs, useLazyQuery accepts the parameter fetchPolicy.

const [lazyQuery, { data, loading }] = useLazyQuery(QUERY, {
  fetchPolicy: 'no-cache'
});

With fetchPolicy set to no-cache, the query's result is not stored in the cache.

Ewing answered 8/6, 2021 at 17:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.