'React useEffect keeps fetching even after stating my dependency
I'm having infinite fetch on my json-server with my useEffect even after I put my dependency for re-rendering after submitting task. It does re-render but in my console I see that it keeps fetching get request. What seems to be lacking on my code. Thank you
function TodoListComponent() {
const [todos, setTodos] = useState([])
const [nameOfTask, setnameOfTask] = useState('')
const url = `http://localhost:3002/todos`
const addTodo = () => {
const task = {nameOfTask}
fetch('http://localhost:3002/todos', {
method: 'POST',
headers: {"Content-type" : "application/json"},
body: JSON.stringify(task)
})
setnameOfTask('')
}
useEffect(() => {
fetch(url).then(res => res.json()).then(data => setTodos(data))
}, [todos])
return (
<div>
<div className='head-container'>
<div className="input-container">
<input type="text" value={nameOfTask} onChange={(e) => setnameOfTask(e.target.value)}/>
<button onClick={() => {
addTodo()
}}>add</button>
</div>
</div>
<div className="todo-container">
{todos.map(todo => (
<div key={todo.id} className="todo-list">
<p>{todo.nameOfTask}</p>
</div>
))}
</div>
</div>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
