skip to Main Content

I want to get first response then second response and then third response in the console section but i can not achieve this. please help me to solve this problem.

this is the outputI tried to solve my problem in this way.

import './App.css';
import { useEffect } from 'react';
import axios from 'axios';
function App() {

  useEffect(() => {
    async function getDataZero() {
      const res = await axios.get(`https://pokeapi.co/api/v2/pokemon/1`);
      console.log("res-0",res)
    }

    async function getDataOne() {
      const res = await axios.get(`https://jsonplaceholder.typicode.com/todos/1`);
      console.log("res-1",res)
    }

    async function getDataTwo() {
      const res = await axios.get(`https://pokeapi.co/api/v2/pokemon`);
      console.log("res-2",res)
    }

    getDataZero();
    getDataOne();
    getDataTwo();

  }, [])

  return (
    <div className="App">
      <header className="App-header">
        <p>React app</p>
      </header>
    </div>
  );
}

export default App;

2

Answers


  1. I have modified your code, in a way so that it will await each promise, and then move to the next.

    import './App.css';
    import { useEffect } from 'react';
    import axios from 'axios';
    function App() {
    
      useEffect( async () => { // <--- use async here
        async function getDataZero() {
          const res = await axios.get(`https://pokeapi.co/api/v2/pokemon/1`);
          console.log("res-0",res)
        }
    
        async function getDataOne() {
          const res = await axios.get(`https://jsonplaceholder.typicode.com/todos/1`);
          console.log("res-1",res)
        }
    
        async function getDataTwo() {
          const res = await axios.get(`https://pokeapi.co/api/v2/pokemon`);
          console.log("res-2",res)
        }
    
       await getDataZero(); // <--- await keyword in front of each function
       await getDataOne();
       await getDataTwo();
    
      }, [])
    
      return (
        <div className="App">
          <header className="App-header">
            <p>React app</p>
          </header>
        </div>
      );
    }
    
    export default App;
    
    Login or Signup to reply.
  2. you can also define a execution function in useEffect

    useEffect(() => {
        ...
        async main() {
            await getDataZero() 
            await getDataOne()
            await getDataTwo()
        }
        main()
    }, [])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search