When I make a get request with Axios to an api I am getting an infinite loop in the useEffect hook and I thought for sure that adding the second option of "[]" would tell it to only run once. Is there something I am missing or overlooked? The console.log is showing me that it is making an infinite loop.
import React, {useEffect, useState} from 'react';
import axios from 'axios';
import { getCookie } from '../utils/util';
const Details = () => {
const [data, setData] = useState(null);
let country;
const queryURL = `/`;
useEffect(() => {
country = getCookie('title');
console.log(country);
axios.get(queryURL + country).then((res) => {
setData(res.data);
}, []);
})
return (
<>
details
</>
)
}
export default Details;
When I make a get request with Axios to an api I am getting an infinite loop in the useEffect hook and I thought for sure that adding the second option of "[]" would tell it to only run once. Is there something I am missing or overlooked? The console.log is showing me that it is making an infinite loop.
import React, {useEffect, useState} from 'react';
import axios from 'axios';
import { getCookie } from '../utils/util';
const Details = () => {
const [data, setData] = useState(null);
let country;
const queryURL = `https://restcountries.eu/rest/v2/name/`;
useEffect(() => {
country = getCookie('title');
console.log(country);
axios.get(queryURL + country).then((res) => {
setData(res.data);
}, []);
})
return (
<>
details
</>
)
}
export default Details;
Share
Improve this question
edited Sep 2, 2021 at 2:18
MrMythical
9,0393 gold badges21 silver badges48 bronze badges
asked Sep 2, 2021 at 2:08
Micah JohnsonMicah Johnson
1222 silver badges12 bronze badges
1 Answer
Reset to default 7You need to put empty array (dependency) after the callback
function:
Change to:
useEffect(() => {
country = getCookie("title");
console.log(country);
axios.get(queryURL + country).then((res) => {
setData(res.data);
});
}, []);