Reputation: 475
I've set up a json-server locally on my machine to use as a mock API for an app that I'm creating. I'm running the server on Port 3004 whilst my app is running on Port 3000. The app functions as expected; however, on inspecting the terminal on which the server is running, I noticed that GET requests are continuously being called every millisecond - see image below:
Is this normal behaviour? I would expect the GET request to be called just once, as per my code below. The GET request is part of a React app and is called inside of useEffect.
useEffect(() => {
fetch('http://localhost:3004/invoices',
{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
}
)
.then(function(response){
return response.json();
})
.then(function(myJson){
setData(myJson);
})
.catch((error) => {
console.error("Error:", error);
});
});
Upvotes: 1
Views: 364
Reputation: 1604
You need to add a dependency to your useEffect
, for example, if you want it to fire only on the first render, you would write it like
useEffect(() => {
fetch('http://localhost:3004/invoices',
{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
}
)
.then(function(response){
return response.json();
})
.then(function(myJson){
setData(myJson);
})
.catch((error) => {
console.error("Error:", error);
});
},[]);
More likely, you will want the effect to fire off when something changes, in that case, add the dependecy to the square brackets like so...
useEffect(() => {
fetch('http://localhost:3004/invoices',
{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
}
)
.then(function(response){
return response.json();
})
.then(function(myJson){
setData(myJson);
})
.catch((error) => {
console.error("Error:", error);
});
},[someState]);
Upvotes: 2