react-apollo icon indicating copy to clipboard operation
react-apollo copied to clipboard

useLazyQuery executed multiple times

Open squarewave24 opened this issue 5 years ago • 1 comments

i have a simple hook component that looks like this

export function DownloadTestData(props) {
  const [getTestData, { loading, error, data }] = useLazyQuery(QUERY_TEST);
  if (data)
     saveAsCsv(data)

  return <Button onClick={getTestData}>export</Button>

it works as expected, except, when the row that contains DownloadTestData component get's re-rendered, it re-runs above function with data still available, so the save executes multiple times (once on click, and all subsequent re-renders of that component)

am i using it incorrectly? how come data remains populated on subsequent re-renders? i need it to trigger only once when getTestData was executed

data is also there for all useEffect hooks subsequent to onClick action.

squarewave24 avatar Jun 11 '20 01:06 squarewave24

the saveAsCsv function should be placed in useLazyQuery's onCompleted. Search onCompleted in https://www.apollographql.com/docs/react/data/queries/#usequery-api.

millievn avatar Jun 24 '20 06:06 millievn