1

I'm trying to add react lazy in my application, and for some reason, it doesn't seem to work.

The component in which I want the lazy load to work on, fetches its data from a server, then it renders the data. The problem is, the component in which the data is getting fetched, which is in the suspense tag, gets loaded before the data actually loads. Here's my code:

AnotherTest.jsx

const AnotherTest = () => {
    const [toDoListData, setToDoListData] = useState([]);

    useEffect(() => {
        async function fetchData() {
            setTimeout(async () => {
                const result = await axios.get(`/api/ToDos/filter/completed`);
                setToDoListData(result.data);
            }, 5000);
        }

        fetchData();
    }, []);

    if (!toDoListData.length) return null;

    return (
        <div>
            {toDoListData.map(item => {
                return <div>{item.name}</div>;
            })}
        </div>
    );
};

Test.jsx

import React, { lazy, Suspense } from 'react';
const AnotherTest = React.lazy(() => import('./AnotherTest'));

const Testing = () => {
    return (
        <div>
            <Suspense fallback={<div>Loading...</div>}>
                <AnotherTest />
            </Suspense>
        </div>
    );
};
Jessica
  • 9,379
  • 14
  • 65
  • 136

1 Answers1

1

The only way I know of that's currently possible is by using fetch-suspense. Read this for a complete article on how he did it.

This would turn your component into

const AnotherTest = () => {
    const toDoListData = useFetch('/api/ToDos/filter/completed', { method: 'GET' });
    return (
        <div>
            {toDoListData.map(item => {
                return <div>{item.name}</div>;
            })}
        </div>
    );
};

If for some reason the fetch-suspense package does not suit your needs the only way is to show a loader in the AnotherTest component itself while fetching the data.

Note that the lazy function is meant for code-splitting and thus lazy loading the JS file, not waiting for anything async in the component itself.

(There is also react-cache but they advice not to use it in real world applications.)

Jap Mul
  • 17,398
  • 5
  • 55
  • 66
  • Thank you for your detailed answer!!! I'm a bit confused... isn't suspense meant for loading data? If not, then what is the point of it? – Jessica May 23 '19 at 15:56
  • 1
    I suggest reading https://reactjs.org/docs/code-splitting.html which explains the (current) use for suspense/lazy. Code splitting is very useful for improving the performance of your app, especially when it comes to dealing with slow connections or large bundles. – Jap Mul May 23 '19 at 16:00