Replies: 1 comment
-
|
The issue is that on the very first render, SWR hasn't kicked off the fetch yet, so The fix is to treat function Stock() {
const { data, isLoading, isValidating } = useSWR(STOCK_API, fetcher);
// data is undefined before the first fetch completes
if (isLoading || data === undefined) return <div className="skeleton" />;
if (data.length === 0) return <div className="empty">no result</div>;
return (
<>
<div>${data}</div>
{isValidating ? <div className="spinner" /> : null}
</>
);
}The key insight: Alternatively, if you want a single clean check, you can use the function Stock() {
const { data, isValidating } = useSWR(STOCK_API, fetcher, { suspense: true });
// data is always defined here because Suspense handles the loading state
if (data.length === 0) return <div className="empty">no result</div>;
return (
<>
<div>${data}</div>
{isValidating ? <div className="spinner" /> : null}
</>
);
}
// Wrap with Suspense boundary
<Suspense fallback={<div className="skeleton" />}>
<Stock />
</Suspense>With |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
As described in the example above, I want to display a “no result” empty state when the fetched data is empty. However, before the data fetching begins — during the initial React render — both isLoading and isValidating are false, which means I can’t return a loading state. As a result, the component mistakenly renders the empty state. How can I correctly detect the state where “the request has not yet started”?
Beta Was this translation helpful? Give feedback.
All reactions