Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop fetch data and store it into state array in Reactjs

I am trying to loop a fetch request based on a array with forEach. How do I store the data in a single array to later render it in JSX?

This is my beginner’s code so far.

import "./App.css";

function Temp2() {
  var payloadArray = [9837, 5021, 0162, 7553];
  let final = [];

  let fetchNewArray = function () {
    payloadArray.forEach((payload) => {
      final.push(
        fetch("API URL", {
          payload,
        })
          .then((res) => res.json())
          .then((json) => {
            let q = json.data.toString(); // q = '1324646'
            return q;
          })
      );
    });

    return Promise.all(final);
  };
  console.log(final); // was expecting final = ["q value 1", "q value 2" ,"q value 3"]
  return (
    <div>
      <header className="App-header">
        <button onClick={fetchNewArray}>GET VALUES</button>
        {final.map((e, i) => {
          return <p key={i}>{e}</p>;
        })}
      </header>
    </div>
  );
}

export default Temp2;

I would appreciate any help

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should call the fetchNewArray using a useEffect when the component load and set the values from Promise.all in a state variable:

function Temp2() {
  const [values, setValues] = useState([]);
  var payloadArray = [9837, 5021, 0162, 7553];

  let fetchNewArray = function () {
    const promises = [];
    payloadArray.forEach((payload) => {
      promises.push(
        fetch('API URL', {
          payload,
        })
          .then((res) => res.json())
          .then((json) => {
            let q = json.data.toString(); // q = '1324646'
            return q;
          })
      );
    });

    Promise.all(promises).then((v) => setValues(v));
  };

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

  return (
    <div>
      <header className='App-header'>
        <button onClick={fetchNewArray}>GET VALUES</button>
        {values.length ? (
          values.map((e, i) => {
            return <p key={i}>{e}</p>;
          })
        ) : (
          <>Loading...</>
        )}
      </header>
    </div>
  );
}

export default Temp2;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading