I have a todo list on my website that looks like this:
When I click the plus button an input appears and I can add an item which adds the item to the database. The problem is that while it does add the item to the database it does not show up on the web page until the page is refreshed. This is the add button:
<div>
<input
type="text"
onChange={(e) => setItem(e.target.value)}
/>
<button onClick={() => itemHandler()}>
Add
</button>
</div>
The itemHandler function just updates the database with the new todo item:
async function itemHandler() {
setAddItem(false)
const res = await fetch('/api/add-todo-item', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id,
item
}),
})
const json = await res.json()
if (!res.ok) throw Error(json.message)
setItem("")
}
But when this function runs the database is updated but the new item does not show up in the website until the page is refreshed.
The todo items are initially passed into the functional component as a parameter:
function ToDoList( {user_id, todo_items} ) { ...
So is there a way to refresh the component and at the same time pass an updated version of the items from the database to the component after the itemHandler adds them to the database?