0
I’m doing a post on my API and want to update my book list whenever I create a new book. My Post is working, but when I add my "list" inside the [list] in use useEffects a Loop is started and the application does not stop generating requests. My list is updated, but Loop does not finish.
I’d like to know the reason for that and a way to resolve it. Thank you!
import React, { useEffect, useState } from "react";
import api from "../../services/api";
function ListaLivros() {
const [lista, setLivros] = useState([])
const novo_livro = {
nome: "Toquinho Book",
valor: 120,
descricao: "A Saga de um Desenvolvedor Desesperado",
produto: "livro"
}
useEffect(() => {
api.get("/lista_livros").then(({ data }) => {
setLivros(data);
console.log(data);
})
}, [lista]);
function addLivro() {
api.post("/lista_livros", novo_livro)
}
return (
<>
<section>
<div className="form ">
<input type="text" className="input" />
<button className="btn btn-primary" onClick={() => addLivro()}>Adicionar Um Novo Livro</button>
</div>
</section>
<section>
<table className="table">
<thead className="thead-dark">
<tr>
<th scope="col">Id</th>
<th scope="col">Nome do Livro</th>
<th scope="col">Valor</th>
<th scope="col">Descrição</th>
<th scope="col">Produto</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
{
lista?.map((lista) => (
<tbody>
<tr>
<th key={lista.id}>{lista.id}</th>
<td>{lista.nome}</td>
<td>{lista.valor}</td>
<td>{lista.descricao}</td>
<td>{lista.produto}</td>
<td><button className="btn btn-warning">Editar</button></td>
<td><button className="btn btn-danger">Excluir</button></td>
</tr>
</tbody>
))
}
</table>
</section>
</>
);
};
export default ListaLivros;
I understood, but if I remove the list from the array I cannot update my list. Please how do I update my list whenever I add a new item?
– Toquinhoro
I believe you can update the status by adding the new item, I will add an example in the reply.
– Gabriel José de Oliveira
It worked, I can do the update. However there is a bug, creating a new book it creates the book but does not display the ID.
– Toquinhoro
Ideally you’d get the answer from your API to be able to update the status, overall it would change the
then
for something like this.then((response) => setLivros(prevValue => [...prevValue, response]))
. but I don’t know for sure what kind of return could vary a lot so I ended up using thenovo_livro
as an example.– Gabriel José de Oliveira