skip to Main Content

I have a little bit problem.

I create data tables in my app and Im getting data from api, but from 2 endpoints.
First call returns me (e.g. offers):

{
 id: 1,
 product_id: 1,
 name: 'some name',
 etc...
}...

And the second one (eg. products):

{
 id: 1,
 name: 'some name',
 etc...
}...

And I wanna get this first array, but in product_id I want to put product name.

I created this:

const [offers, setOffers] = React.useState(null);
const [products, setProducts] = React.useState(null);

React.useEffect(() => {
 fetch(`http://localhost:3000/api/offers`)
 .then((res) => res.json())
 .then((data) => {
  setOffers(data.data);
 });

 fetch(`http://localhost:3000/api/products`)
 .then((res) => res.json())
 .then((data) => {
   setProducts(data.data);
 });
}, []);

But at this point I stopped and I don’t know what to do.

2

Answers


  1. Fetch your products first and then setOffers

    setOffers(offers.map((offer) => (
       {
        ...offer,
        product_name: products.find((product) => product.id == offer.product_id)?.name
       }
     )
    ))
    
    Login or Signup to reply.
  2. Your React code should probably look like this:

    const [offers, setOffers] = React.useState(null);
    const [products, setProducts] = React.useState(null);
    
    React.useEffect(() => {
     const promises = Promise.all([
       fetch(`http://localhost:3000/api/offers`).then((res) => res.json()),
       fetch(`http://localhost:3000/api/products`).then((res) => res.json())
     ]);
     promises.then((
       [offersResp, productsResp]
     ) => {
       const offers = offersResp.data;
       const products = productsResp.data;
       setProducts(products);
       return offers.map((offer) => {
         const product = products.find(pr => pr.id === offer.product_id);
         if(product) {
           return {
             ...offer,
             product_id: product.name
           }
         }
         return offer;
       })
     }).then(offers => {
       setOffers(offers);
     })
     .catch(err => {
       // don't forget to handle errors here
     });
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search