Home > Blockchain >  How do I get data to reload in a React component to show the new data that was just added?
How do I get data to reload in a React component to show the new data that was just added?

Time:01-03

I have a todo list on my website that looks like this:

Todo list

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?

CodePudding user response:

add try{...}catch(error){...} to your app,

also use the hook 'useState' as in something like const [data,setData] = useState([]);

and update it in the try so you'll see it in your page.

CodePudding user response:

Check the response please,

I assume you're getting the updated todos in that request`s response.

So it means you can easily store the new todos(old todos including the new one you just added) in your application state, loop through them, and render them :)

PS: If you're not getting them in your POST request response, you can send a GET request right after your POST request to get all the Todos.

  • Related