restful-react
restful-react copied to clipboard
Cannot detect request errors when using refetch() from useGet() in try/catch
Describe the bug
I want to lazy-fetch some data from our API using refetch from the useGet() hook. Fetching the data should be initiated by clicking a button. I want to show a feedback message in case the data was fetched successfully and an error message if the request failed. I tried this with a simple try/catch, but I'm never running inside the catch block even though the request fails.
import * as React from "react";
import "./styles.css";
import { useGet } from "restful-react";
export default function App() {
const { data, error, refetch } = useGet({
path: "https://xyz.abc",
lazy: true
});
const doFetch = async () => {
try {
await refetch();
// Show success feedback message
console.log("Fetch successful!", data);
} catch (e) {
// Show failure feedback message
console.log("Error during fetch");
}
};
return (
<div className="App">
<button onClick={doFetch}>fetch</button>
</div>
);
}
Expected behaviour
When the request fails (API not available, no internet connection, ...) refetch throws an error.
I read in another issue that useGet() never rejects, so I'm assuming this behaviour is by design and I simply might have the wrong idea of how to use restful-react properly :) If that's the case, I would be grateful for some tips on how to implement the described use case properly. I suppose one could use useEffect() watching for changes on the error property from useGet(), but I'm not sure if that's the way to go.
indeed, there is try/catch inside useGet - but in fact, it doesn't re-throw error like it is done in useMutate.
@fabien0102, was it designed like that? I also see this case described by @jpreis is useful.
btw, there is some input here: https://github.com/contiamo/restful-react/issues/235