stevenH
stevenH

Reputation: 175

Where is the best practice to wait for data fetching and handle logic after?

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

Answers (2)

lala
lala

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

Quentin
Quentin

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

Related Questions