Reputation: 175
I have a component like this:
const [products, setProducts] = useState([]);
const [store, setStore] = useState([]);
const fetchProducts () => {
... fetch('product_url').then((products) => {
setProducts(products);
}).catch();
}
const fetchStore () => {
... fetch('store_url').then((store) => {
setStore(store);
}).catch();
}
useEffect(() => {
fetchProducts();
fetchStore();
}, []);
const handleLogicAfterProductsAndStoresLoadingSuccess = () => {
// products, store
//Some logic here
}
My question is where can I put the handleLogicAfterProductsAndStoresLoadingSuccess()?
Upvotes: 0
Views: 64
Reputation: 1439
you can create another useEffect
to track both changes of products
& store
:-
// handle what happen after products & store fetched
const handleLogicAfterProductsAndStoresLoadingSuccess = (products, store) => {
// if both successfully fetched data (not empty array)
if(products.length > 0 && store.length > 0) {
// do something
} else {
alert('Data not fetched correctly!')
}
}
// handle changes happen to products & store (note: this useEffect will be fired every time there are changes made to the products & store)
useEffect(() => {
handleLogicAfterProductsAndStoresLoadingSuccess(products, store)
}, [products, store])
Upvotes: 1
Reputation: 943216
Generally, just test for the values inside your render function, and put any processing after the request.
// Testing for length because you are initializing them to empty arrays. You should probably use null instead.
if (!(products.length && store.length)) {
return <LoadingComponent />
}
// Any other processing you need goes here
return <>
{/* Your result goes here */}
</>;
Upvotes: 1