简体   繁体   中英

Retrying failed graphql query with react hooks?

I have the following example component and I'm hoping when there is a random failure, I can click a button to retry the query manually (through some user interaction). Is this possible by chance? I would also like if the resultant query is successful, then the page gets populated with the data (ie a rerender of sorts).

export default () => {
  let { loading, error, data } = useQuery(myGqlQuery)

  if (loading) {
    return <LoadingComponent />
  }

  const reassign = () => {
    // I want this function to somehow retry the query to see if error has subsided
  }

  if (error) {
    return <button onClick={reassign}>Retry Query</button>
  }

...

use refetch() as const {..., refetch} = useQuery(QUERY)

see docs: https://www.apollographql.com/docs/react/data/queries/

You can use refetch :

export default () => {
  const { loading, error, data, refetch } = useQuery(myGqlQuery)

  if (loading) {
    return <LoadingComponent />
  }

  const reassign = () => {
    refetch()
  }

  if (error) {
    return <button onClick={reassign}>Retry Query</button>
  }
  
  return (
    <div>
      // render your data here
    </div>
  )
}

You can use useLazyQuery instead of useQuery .

https://www.apollographql.com/docs/react/data/queries/#executing-queries-manually

In this way you have to call manually also at the first render inside a useEffect hook but it is easy.

export default () => {
  let [fnToCallQuery, { loading, error, data }] = useLazyQuery(myGqlQuery)

  React.useEffect(() => fnToCallQuery(), []);

  if (loading) {
    return <LoadingComponent />
  }

  if (error) {
    return <button onClick={_ => fnToCallQuery()}>Retry Query</button>
  }

  // return your jsx with fetched data

Something like the above code :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM