0

I am trying to fetch data from another fetched data by id, then display them together in a card using react hooks. I am getting an empty array error in the console. Any help would be greatly appreciated. Also not sure if I am storing the data correclty in state.

const CardContainer = () => {
  const [work, setWork] = useState([]);
  const [work2, setWork2] = useState([]);

  useEffect(() => {
    fetch("https://www.hatchways.io/api/assessment/work_orders")
      .then((response) => response.json())
      .then((data) => {
        console.log(data.orders);
        data.orders.map((order) => {
          console.log(order.workerId);
          fetch(
            `https://www.hatchways.io/api/assessment/workers/${order.workerId}`
          )
            .then((res) => res)
            .then((data) => setWork2(data));
        });
      });
  }, []);
  console.log(work);
  return (
    <div>
      <h2>Cards</h2>
      {work.map((items, index) => (
        <CardUI key={index} props={items} />
      ))}
    </div>
  );
};

enter image description here

skyboyer
  • 22,209
  • 7
  • 57
  • 64
cyberAnn
  • 411
  • 1
  • 7
  • 16
  • I know next to nothing about React, but this is probably another duplicate of the good old [How do I return a response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Jeremy Thille Jul 07 '21 at 10:09
  • 1
    1. First this you are assigning data in `work2` ( `setWork2(data)`), but you are using `work` while displaying data. 2. `console.log(work);` You are printing data outside the then but it won't print. 3. `data.orders.map` You are iterating on data.orders and inside that iteation you are calling an API. So here you have to push resulted data in an array. Setting them directly like `setWork(data)` replaces the old data. – Surjeet Bhadauriya Jul 07 '21 at 10:11
  • how can I show both work id and orders ids in one card? I can only seem to get workers id in the cards. – cyberAnn Jul 07 '21 at 18:38

3 Answers3

0

Try

fetch('https://www.hatchways.io/api/assessment/work_orders')
    .then((response) => response.json())
    .then((data) => {
        const respones = data.orders.map((order) =>
            fetch(`https://www.hatchways.io/api/assessment/workers/${order.workerId}`).then((res) => res.json()),
        );

        Promise.all(respones).then((fetchedOrders) => {
            setWork2(fetchedOrders);
        });
    });

If you have more specific question please ask in the comment

jkaczmarkiewicz
  • 1,500
  • 6
  • 17
  • Thank you. I am trying to display orders that match the ids of workers together on a card. Is it possible to map matching order workerIds to worker id on a card? – cyberAnn Jul 07 '21 at 11:26
0

When you use map to create a new array of promises you should use Promise.all to wait until they've all either been resolved or been rejected. Then you can map over that JSON, parse it, and add it to state.

fetch('https://www.hatchways.io/api/assessment/work_orders')
  .then(response => response.json())
  .then(data => {
    const orders = data.orders.map(order => {
      fetch(`https://www.hatchways.io/api/assessment/workers/${order.workerId}`)
    });
    Promise.all(orders).then(data => {
      setWork2(data.map(data => JSON.parse(el));
    });
});
Andy
  • 61,948
  • 13
  • 68
  • 95
  • Thank you. I am trying to display orders that match the ids of workers together on a card. Is it possible to map matching order workerIds to worker id on a card? – cyberAnn Jul 07 '21 at 11:32
0
const CardContainer = () => {

const [work, setWork] = useState([]);
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    fetch('https://www.hatchways.io/api/assessment/work_orders')
      .then((response) => response.json())
      .then((data) => {
        const respones = data.orders.map((order) =>
          fetch(`https://www.hatchways.io/api/assessment/workers/${order.workerId}`).then((res) => res.json()),
        );
        Promise.all(respones).then((fetchedOrders) => {
          setWork(fetchedOrders);
          setIsLoading(false)
        });
      });
  }, []);

  return (
    isLoading ? <div>Loading</div> : <div>
      <h2>Cards</h2>
      {work.map((item, index) => (
        <div key={index} props={item}>{item.worker.companyName} </div>
      ))}
    </div>

  )
}
  • i have added loading and showing company name in card output enter image description here
Avani Bataviya
  • 750
  • 1
  • 6
  • 20
  • Hi @AvaniBataviya , Thank you. I am trying to display orders that match the ids of workers together on a card. Is it possible to map matching order workerIds to worker id on a card? – cyberAnn Jul 07 '21 at 11:25
  • yes you can do.. find same id from work array and then print data of it. Below link will useful to you. https://stackoverflow.com/questions/19395257/how-to-count-duplicate-value-in-an-array-in-javascript?answertab=active#tab-top – Avani Bataviya Jul 07 '21 at 11:35
  • the only thing I can print and get is the workers id, I can not get any orders id. I also need to print out orders ids – cyberAnn Jul 07 '21 at 18:29
  • are you saying that I should use a for loop? – cyberAnn Jul 07 '21 at 20:06