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>
    );
};
4

1 回答 1

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.)

于 2019-05-23T08:53:05.503 回答