PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How make useEffect work with chaining async/wait map?

 October 13, 2022     api, axios, reactjs     No comments   

Issue

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;

Solution

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) => {


Answered By - David
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing