最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting infinite loop when making an axios get request - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 7

You 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);
  });
}, []);
发布评论

评论列表(0)

  1. 暂无评论