First call to ReactContext is setting the isLoading sate to false

笑着哭i 提交于 2021-01-28 06:55:50

问题


I have Component A and Component B that both uses the same ReactContext to fetch the data. Whichever component calls the context first, at the end of fetching the data, the Context sets the isFetchingData state to false.

Now, when the second component calls the context the isFetchingData state is already set to false. Therefore, it renders the component without waiting for the data.

To illustrate:

ComponentA => isFetchingData? true => getsData => sets isFetchingData to false. => renders component

ComponentB => isFetchingData? false => renders the component => getsData => sets isFetchingData to false (already false)

How can I address this?

Following is my code.

Context:

    const [allEmployees, setAllEmployees] = useState([]);
    const [isFetchingData, setIsFetchingData] = useState(true);

    useEffect(() => {
        getAllEmployees().then(
            //doing something
        ).then(employees => {
            setAllEmployees();
            setIsFetchingData(false);
        });
    }, [])

Component:

const ComponentB = () => {

    const {
        allEmployees,
        isFetchingData
    } = useContext(MyContext);


    if(isFetchingData) {
        return <p>'Loading'</p>; // it never hits this as its false
    }

    return (
    // if data is loaded render this
    );
};

来源:https://stackoverflow.com/questions/64462393/first-call-to-reactcontext-is-setting-the-isloading-sate-to-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!