React suspense for component that takes an API call?

74 views Asked by At

Im looking to render a header based on an API call. Before the API returns the data, it is undefined. My render looks like this:

const LazyHeader = async () => {
  const data = await fetchCampaignHeaderData({ client });
  return <CampaignHeader data={data} />;
};

<Suspense fallback={<SkeletonHeader />}>
  <LazyHeader />
</Suspense>

This works, although I get 4 errors about a bad request (400) and Invalid JSON. If I switch it to the old method of useEffect and useState I get none of these errors. Old method:

useEffect(() => {
 (async () => {
   Promise.all([fetchCampaignHeaderData({ client })]).then(async (data) => {
     const header = data[0];
     setDataHeader(header); // useState variable
     setLoading(false); // useState variable
   });
 })();
}

{ loading ? <SkeletonHeader /> : <CampaignHeader data={dataHeader} /> }
1

There are 1 answers

4
natashap On

It is always a good practice and React recommended method to make all API calls inside useEffect hook.

Try the following:

const LazyHeader = () => {
    const [data, setData] = useState();

    useEffect(async () => {
        const data = await fetchCampaignHeaderData({ client });
        setData(data[0]);
    }, []); 

    return <CampaignHeader data={data} />;
};