I want to use the react-error-bounary package and suspense to handle asynchronous handling in the asynchronous processing method using isLoading and isError, which are normally operating in useQuery. The code below is the code using the react-error-boundary package and suspense.
Routers.tsx
const chartError = () => ( //fallback component of errorBoundary
<h1>error occur!</h1>
)
function Router() {
return (
<BrowserRouter>
<Routes>
...skip
<Route path='chart' element={
<ErrorBoundary FallbackComponent={chartError}>
<Suspense fallback={<h1>Loading</h1>}>
<CoinChart/>
</Suspense>
</ErrorBoundary>
}/>
</Routes>
</BrowserRouter>
);
}
coin_chart.tsx
export function CoinChart() {
const {coinId} = useParams();
//useQuery to call api inside CoinChart component
const {data} = useQuery<IHistorical[]>(['coinHistory', coinId], () => fetchCoinHistory(coinId), {suspense: true, useErrorBoundary: true});
return (
<>
{<Line data={coinData} options={options} />}
</>
)
}
coin_api.ts
//coinChart component's queryFn function
export async function fetchCoinHistory(coinId: string | undefined) {
const response = await fetch(`https://ohlcv-api.nomadcoders.workers.dev?coinId=${coinId}`, {method: 'GET'})
if (!response.ok) {
throw new Error();
}
return response.json();
}
If throw new Error() was thrown in fetchCoinHistory, it was expected that ErrorBoundary of Routers.tsx would detect the error and show <h1>error occur!</h1>, the result value of FallbackComponent.
But when the api call throws an error, the browser throws an error like below
Uncaught runtime errors:
ERROR
Error
at fetchCoinHistory (http://localhost:3000/static/js/bundle.js:1236:11)
Suspense's fallback works normally, but ErrorBoundary's FallbackComponent does not work normally. please tell me the cause
I wrote it using Google Translate, so please forgive me :)