Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda