ISilva
ISilva

Reputation: 13

Having issues passing data of a multiple fetch API into an array to access outside the function

trying to fetch data from multiple APIs and pass it to an array. data is fetched and passed only inside the function. used an useState to set the data, only one of the data get passed into the array at last. Used Promise.all method too, but still gives the same results and infinite loops when data is set to the usestate.

import React, { useEffect, useState } from 'react';

export default function GetFirebaseRFID() {

  const [rfidData, setRfidData] = useState([]);
  let arrayList = ['24637310', '1182372559', '2022916526'];
  var dataArray = [];

  useEffect(() => {
    arrayList.forEach((element) => {
      fetch(`https://localhost:44301/api/unit/rfid/${element}`)
      .then(res => res.json())
      .then(data => {
        dataArray.push(data);
        setRfidData(dataArray);
      })
    });
  }, [])



  return (
    <>
      {console.log(rfidData)}
      {rfidData.map(data=> {
      return (
      <tr>
        <td>{data.itemID}</td>
        <td>{data.price}</td>
        </tr>
        )
      }
      )}

      
    </>
  );
}

enter image description here

Code and consoleLog output

Upvotes: 1

Views: 1054

Answers (2)

SonerGG
SonerGG

Reputation: 11

Can you try this:

function YourComponent() {
  const [data, setData] = useState([]);

  useEffect(() => {
    getDataHandler();
  }, []);

  const getDataHandler = async () => {
    const arrayList = ['24637310', '1182372559', '2022916526'];
    const finalData = [];

    for (const item of arrayList) {
      const response = await fetch(`URL_OF_YOUR_API_WITH_${item}`);
      const resData = await response.json();
      finalData.push(resData);
    }

    setData(finalData);
  };

  return (
    <table>
      <tbody>
        {data.map((item) => (
          <tr key={item.itemID}>
            <td>{item.itemID}</td>
            <td>{item.price}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

Upvotes: 1

yondu_udanta
yondu_udanta

Reputation: 807

You are only seeing one entry because in the array because you are mutating the dataArray and setting it to the state again which does not trigger a re-render of the component. I would rather split the logic into two components instead of querying for all the 'rfid's in one component, I would have a RFID component that takes the RFID as the prop and queries the API in it's useEffect for only one RFID it received.

function RFID({ id }) {
const [data, setData] = useState('');

useEffect(() => {
    fetch(`https://localhost:44301/api/unit/rfid/${id}`)
      .then(res => res.json())
      .then(data => {
        setData(data);
      })
  }, [])
 
  return (
    <tr>
      <td>{data.itemID}</td>
      <td>{data.price}</td>
    </tr>
  );
}

export default function GetFirebaseRFID() {

  let arrayList = ['24637310', '1182372559', '2022916526'];

  return (
    <>
      {arrayList.map(id => <RFID id={id} />)}   
    </>
  );
}

Upvotes: 0

Related Questions