Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
How do I get data to reload in a React component to show the new data that was just added?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!