Why is axios waiting for the previous request before executing the next one

  axios, javascript, reactjs
I am facing a serious problem and cannot find the answer
Here are my components

App.js:

import './App.css';
import Component1 from './Component1'
import Component2 from './Component2'

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <Component1 />
        <Component2 />
      </header>
    </div>
  );
}

export default App;

Component1.jsx:

import { useState, useEffect } from 'react'
import API from './api'

let Component1 = () => {
  let [isLoading, setIsLoading] = useState(true)
  useEffect(() => {
    let fetch = async () => {
      await API.one()
      setIsLoading(false)
    }
    fetch()
  }, [])
  return (
    <div>
      {isLoading && 'Loading...'}
      {!isLoading && 'Loaded!'}
    </div>
  )
}

export default Component1

Component2.jsx:

import { useState, useEffect } from 'react'
import API from './api'

let Component2 = () => {
  let [isLoading, setIsLoading] = useState(true)
  useEffect(() => {
    let fetch = async () => {
      await API.two()
      setIsLoading(false)
    }
    fetch()
  }, [])
  return (
    <div>
      {isLoading && 'Loading...'}
      {!isLoading && 'Loaded!'}
    </div>
  )
}

export default Component2

api.js:

import * as axios from 'axios'

let instance = axios.create({
  baseURL: `http://localhost/`
})

let API = {
  one() {
    return instance.get('test?sleep=1').then(res => res.data)
  },
  two() {
    return instance.get('test?sleep=2').then(res => res.data)
  }
}

export default API

I pass the delay value in seconds and the script waits.
But in the console I see that the second component is waiting for the first to execute the command. As a result, API.one takes 1 second and API.two takes 3 seconds. It turns out that they work synchronously and until the first component returns the result, the second waits for it! What to do?

Source: Ask Javascript Questions

LEAVE A COMMENT