By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – App component keeps calling the axios.get many times over in a react function
JavaScript

Javascript – App component keeps calling the axios.get many times over in a react function

Admin
Last updated: 2023/12/13 at 5:45 PM
Admin
Share
4 Min Read
App component keeps calling the axios.get many times over in a react function

Problem:

In my App function (reactjs here), I am making a call to an api, and then in the .then I am making many more api calls with await to get more details. This is an illustration using a public api for pokemon. The main call loads a summary, then each record is called again to fill in the details.

Contents
Problem:Solution:

The problem I am having is that App() is called many, many times, and so the api calls are repeated over and over eventually leading to the browser to crash. I think the reason why is that I am updating the progress state as I move through the loop which causes the function to rerun. But I’m not sure how to stop it calling the initial axios.get again.

import './App.css';
import axios from 'axios';
import React, {useState} from 'react'
import "./styles.css"

function App() {
  let [allDataJson, setAllData] = useState(null);
  let [progress, setProgress] = useState(0);
      axios.get("https://pokeapi.co/api/v2/pokemon/?offset=0&limit=200").then(async (response) => {
          const newData = [];
          // API returns result in blocks, with next pointing to next block
          do{
            for(var item of response.data.results)
              newData.push(item);
            response = await axios.get(response.data.next);
          } while(response.data.next);
          for(const item of newData) {
            item.detail = await getDetails(item.url);
            setProgress(progress+1);
          }
          setAllData(JSON.stringify(newData));
        });
  return (
    <div>
      { allDataJson ? (
        <div>Completed Load</div>
      ) : (
        <div>Loading, please wait....{progress}</div>
      )
    }
    </div>
  );
}
const cache = {};

export async function getDetails(url) {
  // url is in form "host/.../id/" where id is unique number.
  const split = url.split('/');
  const code = 'code' + split[split.length - 2];
  if(cache.hasOwnProperty(code))
    return cache[code];
  else {
    const response = await axios.get(url);
    const data = response.data;
    cache[code] = data;
    return data;
  }
}

export default App;

I tried this ugly hack. This did prevent it from calling the api too many times but the html did not render.

function App() {
  let [allDataJson, setAllData] = useState(null);
  let [progress, setProgress] = useState(0);
  if(!started) {
      started = true;
      axios.get("https://pokeapi.co/api/v2/pokemon/?offset=0&limit=200").then(async (response) => {
... same as above ...
        });
      }
  return (
    <div>
      { allDataJson ? (
        <div>Completed Load</div>

What am I doing wrong? Is there a better way to achieve this goal. (It takes a while to load all this, so really I’d like a simple progress bar, or maybe even a background “thread” as in a setTimeout to do the same thing.)

Obviously, fairly new to react

Solution:

You should wrap the axios call in a useEffect function.

Import useEffect alongside useState at the top:

import React, {useState, useEffect} from 'react'

And you App function should look more like this:

function App() {
  let [allDataJson, setAllData] = useState(null);
  let [progress, setProgress] = useState(0);
  useEffect(() => {
    axios.get...
  }, []) // notice the empty array will cause the function to only be called once when the app loads since it is not dependent on any other variables.
  return (
   ...
  );
}

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Selecting a set of colors, making a new layer, and then sending to that layer using Illustrator script Javascript – Selecting a set of colors, making a new layer, and then sending to that layer using Illustrator script
Next Article How to get the date for a specific time zone [closed] Javascript – How to get the date for a specific time zone [closed]
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?