import { useState, useEffect } from "react";
import { ListItem } from "./ListItem";
export const TodoInput = props => {
const [description, setDescription] = useState("");
const [todos, setTodos] = useState([]);
const handleChange = event => {
setDescription(event.target.value);
};
const updateTodos = async () => {
const response = await fetch("http://localhost:5000/todos");
const jsonData = await response.json();
setTodos(jsonData);
};
useEffect(() => {
updateTodos();
}, [description]);
const handleSubmit = e => {
e.preventDefault();
e.stopPropagation();
const body = { description };
fetch("http://localhost:5000/todos", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
setDescription("");
};
return (
<>
<div className="list-input">
<form onSubmit={handleSubmit}>
<input value={description} onChange={handleChange} />
<button type="submit">Add todo</button>
</form>
</div>
<div className="todo-list">
<ul>
{todos.map(e => (
<ListItem todoItem={e} key={e.id} />
))}
</ul>
</div>
</>
);
};
I have this react component which is basically just a form that calls to an api when submitted. Both the enter key and the submit button works fine but only if you use that method only. For example: if I enter one item by pressing the submit button, it instantly pops up in the list and if I do it again, the same thing happens. But if I then write somehing and press enter, the textbox clears and the item is sent through the api to the database but it won't show up in the list until i type a character into the input field again. Does this have something to do with useEffect() not being called or is it something else?