So i have a simple to-do app, click here to [Link removed].
The problem i have is that in Console > Network i get too many same GET
requests so it looks like i have an infinite loop. Im probably not coding this right in useEffect, since the effect triggers my http get methods which contain setTodos(data) which makes it trigger useEffect again.
What im trying to achieve is the same functionality that the web app has right in this moment, but with appropriate coding:
EDIT: What i tried right now is implementing useState [test,setTest]
. I added setTest(!test)
to my funcs: addTodo
, removeTodo
, markTodo
and to my category btn onClick
func. I also put [test]
to dep. array in my useEffect. Sometimes list updates correctly, sometimes it doesnt at all, and sometimes it udpates but incorrectly (ex: when i mark a todo, it gets marked/crossed and then it gets unmarked 1sec after. But if i refresh the page its ok).
useEffect
useEffect(() => {
if(filter === 'Completed')
httpRequestHandler(`${baseAPIurl}/completed`, "GET");
else if(filter === 'Active')
httpRequestHandler(`${baseAPIurl}/notcompleted`, "GET");
else
httpRequestHandler(`${baseAPIurl}/todos`, "GET");
});
And here is part of my httpRequestHandler function
const httpRequestHandler = async (url, type, data) =>
{
let request = {}
if(type === 'GET')
{
request = {
method: "GET",
headers: {"Content-type": "application/json"}
};
await fetch(url, request)
.then((response)=> {
return response.json();
})
.then((data)=> {
setTodos(data);
});
return;
}
...........................
}
Depending on the rest of your code, you need to adjust the dependency array
more info, eg. here
Have you tried adding filter
into dependency array to only update on filter change?
useEffect(() => { ... }, [filter])
No idea what was causing my useEffect not to trigger in the first place, i already tried this but now it works (no idea why). What i did is:
useState [trigger, setTrigger]
httpHandler
func (which handles http requests), specifically in PUT/DELETE/POST part of the func where i use fetch(--, --) i added setTrigger(!trigger)
to .then()
part.[trigger]
to useEffect dependency array
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.