Quiero implementar este escenario mediante react-query :
Mi componente obtiene una API y debe intentarlo una vez cuando se desconectó Internet del cliente y nunca volver a recuperar si se volvió a conectar Internet... y después de 3 segundos si el reintento no tuvo éxito, debería mostrar un error con un botón para volver a intentar la solicitud.
const URL = 'https://randomuser.me/api/?results=5&inc=name'; const Example = () => { const { error, data, isLoading, refetch } = useQuery('test', () => fetch(URL).then(response => response.json()).then(data => data.results), { refetchOnWindowFocus: false, refetchOnReconnect: false, retry: 1, retryDelay: 3000 }); if (isLoading) return <span>Loading...</span> if (error) return <span>Error: {error.message} <button onClick={refetch}>retry</button></span> return ( <div> <h1>Length: {data ? console.log(data.length) : null}</h1> <button onClick={refetch}>Refetch</button> </div> ) } Al considerar el código anterior, configuré refetchOnReconnect: false para deshabilitar la recuperación después de que se conectó a Internet, retry: 1 para configurar una vez intentar y retryDelay: 3000 para establecer un límite para el tiempo de reintento.
Pero cuando uso Throttling -> offline en DevTools, después de hacer clic en el botón solo muestra el último resultado y no muestra el error y el botón de reintento después de 3 segundos...
Entonces, ¿hay alguna forma de manejar esta función?
React-query está usando los datos en el caché, debe invalidar la consulta para obtener los datos nuevamente llamando a la función invalidateQueries :
onst URL = 'https://randomuser.me/api/?results=5&inc=name' const Example = () => { // Get QueryClient from the context const queryClient = useQueryClient() const { error, data, isLoading, refetch } = useQuery( 'test', () => fetch(URL) .then(response => response.json()) .then(data => data.results), { refetchOnWindowFocus: false, refetchOnReconnect: false, retry: 1, retryDelay: 3000 } ) const buttonClickHandler = () => queryClient.invalidateQueries('test') // <=== invalidate the cache if (isLoading) return <span>Loading...</span> if (error) return ( <span> Error: {error.message} <button onClick={refetch}>retry</button> </span> ) return ( <div> <h1>Length: {data ? console.log(data.length) : null}</h1> <button onClick={buttonClickHandler}>Refetch</button> </div> ) }