Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
infinite api calls within few seconds Reactjs

I have a Home component in which I call an api, get the data and store in in a state. And finally display the data in an arranged way. Here is the code

import React, { useContext } from "react";
import styled from "styled-components";
//import context
import MainContext from "../context/MainContext";
//api
import { homeDataURL, topSearchesURL } from "../api/base";
import { getResponse } from "../api";

const Home = () => {
  const { topSearches, setTopSearches } = useContext(MainContext);
  getResponse(
     topSearchesURL(),
       (data) => {
         setTopSearches(data);
       },
       (err) => alert(err)
  );  
  return <div></div>;
};

export default Home;

And the getResponse() function

export const getResponse = (url, callback, errcallback) => {
  axios
    .get(url)
    .then((data) => {
      if (callback != null) {
        callback(data.data);
      }
    })
    .catch((err) => {
      if (errcallback != null) {
        errcallback(err);
      }
    });
};

But this function goes to an infinite loop with numerous api hits, i want this to run just one time when the Home component loads.

There is a React hook useEffect which needs a dependecy array, leaving it blank like this

useEffect(() => {
    getResponse(
        topSearchesURL(),
        (data) => {
          setTopSearches(data);
          console.log(data)
        },
        (err) => alert(err)
      );
  }, [])

gives a warning React Hook useEffect has a missing dependency: 'setTopSearches'. Either include it or remove the dependency array react-hooks/exhaustive-deps Removing the array dependency is not an option, so what should I do? Is there any other way to do this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are not returning Axios promise, and also no need to use callback use async/await.

export const getResponse = (url) => axios.get(url).then((data) => data.data);

// Component
const apiUrl = topSearchesURL();
useEffect(() => {
  const run = async () => {
    try {
      const data = await getResponse(apiUrl);
      setTopSearches(data);
    } catch (error) {
      alert("Something went wrong");
    }
  };
  run();
}, [apiUrl]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!