Home > database >  How make useEffect work with chaining async/wait map?
How make useEffect work with chaining async/wait map?

Time:08-12

I'm making an API call and then afterwards there is a chaining async/await.

When the page loads, the code is not executing the chaining part, I'm getting just the arrayDrivers.

How can I make the useEffect perform the chaining async/wait when the page loads?

import { useState, useEffect } from "react";
import DriversList from "../components/DriversList";
import axios from "axios";

const GetDrivers = () => {
  const [drivers, setDrivers] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchDriver = async () => {
      const res1 = await axios.get("http://ergast.com/api/f1/2022/drivers.json?limit=25");
      const arrayDrivers = res1.data.MRData.DriverTable.Drivers;
      setDrivers(arrayDrivers);
      await Promise.all(
        drivers.map(async (driver) => {
          const searchTitle = `/api.php?action=query&generator=search&format=json&gsrsearch=${driver.givenName}_${driver.familyName}&gsrlimit=1&prop=info`;
          const res2 = await axios.get(searchTitle);
          const driverTitle = Object.values(res2.data.query.pages)[0].title;
          const linkPhoto = `/api.php?action=query&titles=${driverTitle}&prop=pageimages&format=json&pithumbsize=400`;
          const res3 = await axios.get(linkPhoto);
          const thumbSource = Object.values(res3.data.query.pages)[0].thumbnail.source;
          driver.photo = thumbSource;
          console.log(driver);
        }, setIsLoading(false))
      );
    };
    fetchDriver();
    // eslint-disable-next-line
  }, []);
  return <>{isLoading ? <p>Loading...</p> : <DriversList drivers={drivers} />}</>;
};

export default GetDrivers;

CodePudding user response:

You're updating state before you've finished modifying your data:

setDrivers(arrayDrivers);
await Promise.all(
  //...
);

Modify the data, then use that data to update state:

await Promise.all(
  //...
);
setDrivers(arrayDrivers);

Additionally, you're not modifying the actual data. You're trying to modify the empty array from state:

drivers.map(async (driver) => {

The data you got from the server is in arrayDrivers:

arrayDrivers.map(async (driver) => {
  • Related