Home > database >  Promise all statement in react
Promise all statement in react

Time:09-01

I have just started learning react. I want to fetch data from Api and display in browser . In log i am getting two urls but in browser as i am using use state it is updating. Could someone please help ?

Code :


import { useState } from "react";
import "./styles.css";
export default function App() {
  // const [url, setUrl] = useState([]);
  const [arrData, setArrData] = useState([]);
  const fetchApi = () => {
    let url1 = fetch("https://randomuser.me/api");
    let url2 = fetch("https://randomuser.me/api");
    Promise.all([url1, url2])
      .then((files) => {
        files.forEach((data) => {
          process(data.json());
        });
        
      })
      .catch((err) => {});
    let process = (prom) => {
      prom.then((data) => {
        setArrData(data.results[0].picture.large);
        console.log(data.results[0].picture.large);
        
      });
    };
  };
  return (
    <div className="App">
      <button onClick={fetchApi}>Fetch</button>
      <div>
        <img src={arrData} alt="random"></img>
        
      </div>
    </div>
  );
}

CodePudding user response:

I would write the methods for which I use in Promise.all(). The methods for url1 and url2 can be written as:

const [dataOne, setDataOne] = useState([]);
const [dataTwo, setDataTwo] = useState([]);

const getDataOne = async () => {
  const response = await axios.get('...');
  setDataOne(response.data);
}

const getDataTwo = async () => {
  const response = await axios.get('...');
  setDataTwo(response.data);
}

Then, preferably in useEffect hook, you can call Promise.all() such as:

useEffect(() => {
  Promise.all([getDataOne(), getDataTwo()]).then(values => {
    console.log(values);
  }).catch(error => {
    console.log(error);
  });
}, []);
  • Related