Here is the code to initialize categoryArray
. I want to run the useEffect
only if the categoryArray
data changes.
const [categoryArray, setCategoryArray] = useState([]);
useEffect(() => {
axios.get('http://localhost:8080/user/category')
.then(response => {
if (categoryArray !== response.data.category) {
setCategoryArray(response.data.category);
}
})
.catch(err => {
console.log(err);
})
}, [categoryArray])
I tried to apply a conditional statement to setCategoryArray
only if there is some change but somehow that conditional statement is not working properly and an infinite loop is happening.
Could you please guide me on where I am getting wrong, also let me know if more information is required.
CodePudding user response:
The last parameter of a useEffect
marks on what value changes the useEffect
should be triggered again.
Since you're setting categoryArray
with the value of the axios
call, but also configured the useEffect
to be triggered when that variable changes, it will trigger again and again.
You probably can just remove the [categoryArray]
so the useEffect
is only triggered once on the initial render.
CodePudding user response:
as can be seen in your code you have categoryArray in dependency array , and inside useEffect callback you are updating it,which cause it to generate infinite loop,if you need to load data only one time you just need to remove it from dependency,like
useEffect(() => {
axios.get('http://localhost:8080/user/category')
.then(response => {
if (categoryArray !== response.data.category) {
setCategoryArray(response.data.category);
}
})
.catch(err => {
console.log(err);
})
}, [])
or you can inside callback make sure that api call only executed if categoryArray.length==0,like this
useEffect(() => {
if(categoryArray.length>0)return;
axios.get('http://localhost:8080/user/category')
.then(response => {
if (categoryArray !== response.data.category) {
setCategoryArray(response.data.category);
}
})
.catch(err => {
console.log(err);
})
}, [categoryArray])
this way it will only make api call when array is empty