问题
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