How to add callback to useLazyQuery

Viewed 4215

I'm doing the tutorial - https://www.apollographql.com/docs/react/data/queries/ with a lazy graphQL. I have a function which let me get data by click button with lazy query to server. I wrapped it of anonymous function and put to onClick button. Could you help me to add another function to callback of getDog, to add some actions after useLazyQuery will finished.

const [getDog, { loading, data }] = useLazyQuery(GET_DOG_PHOTO);  

I tried

const [getDog, { loading, data }] = {
    useLazyQuery(CUSTOM_GQL);
    return // some actions with data and return;
}

does not compile

<button onClick={
   () => {
      getDog();
      return // some actions
          }
        }

some actions works only after second click.

1 Answers

'Classic' callback can be defined inside hook (see API specs)

const [getDog, { loading, data }] = useLazyQuery(GET_DOG_PHOTO, {
  onCompleted: (data) => {
    // some actions
  }
});

return (
  <button onClick={ () => getDog() ) 

... but in react and in functional components (with hooks) component function is rerun on changes to update view

const [getDog, { loading, data }] = useLazyQuery(GET_DOG_PHOTO);  

if( data ) {
  // 'callback'
}

... but this code can be run many times (by other changes) ... you can avoid that with useEffect hook:

useEffect(() => {
  // code run only on every `data` change
  if( data ) {
    // only when `data` not empty - after first and futher data loading
  }
}, [data]);
Related