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?
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]);