I want to display some datas from API using functional component instead of class component in react. In order to do so, I write useEffect and apparently work properly. The problem is, if I write console log, it would return an infinite value.
Any one can help me to solve this? I want the console log stop looping the value from my API. This is my source code. Thank you.
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
export default function FoodDetail() {
const { id } = useParams();
const [detail, setDetail] = useState([]);
useEffect(() => {
axios
.get("http://localhost:3004/foods/" id)
.then((res) => {
setDetail(res.data);
console.log(detail)
})
.catch((error) => {
console.log(error);
});
});
return ()
}
CodePudding user response:
if you want the get to only run once on component mount, you can use the code below:
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
export default function FoodDetail() {
const { id } = useParams();
const [detail, setDetail] = useState([]);
useEffect(() => {
axios
.get("http://localhost:3004/foods/" id)
.then((res) => {
setDetail(res.data);
console.log(detail)
})
.catch((error) => {
console.log(error);
});
}, []);
return ()
}
The only difference is the inclusion of an empty dependency array as the second argument for useEffect()
. Going forward, if you want to refetch this data based on the state of another variable changing, you can add that variable to the dependency array and this will refetch the data each time the value of that variable changes.
** edit **
To see the value of detail
properly, you can remove the console.log from the first useEffect loop and add something like this to the code:
useEffect(()=> {
console.log(detail)
}, [detail])
CodePudding user response:
your useeffect is running infinitely since you console log your call stack gets full and you notice it so use following code so it will exactly run once like componentdidmount
useEffect(() => {
axios
.get("http://localhost:3004/foods/" id)
.then((res) => {
setDetail(res.data);
console.log(detail)
})
.catch((error) => {
console.log(error);
});
},[]); //add empty array as another parameter of useEffect so it run only
//once
CodePudding user response:
Try adding an empty array to the UseEffect refreshing dependency.
UseEffect(() => {}, [])
this empty array means UseEffect will only be triggered at component mounting, i guess yours would be called everytime component is re-rendered.
Example : UseEffect(() => {console.count('refresehd'), [detail]})
would be triggered everytime your detail changes
for more info check the UseEffect Documentation
Docs useEffect