Request Loop in useEffect

Asked

Viewed 24 times

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;

1 answer

1


Your problem is in your dependencies list useEffect, see that you pass lista in the array of dependencies, and internally you update this state after the request is completed, making this you change the value of lista and the useEffect loop. In general you just remove the list of dependencies from the useEffect.

    useEffect(() => {
        api.get("/lista_livros").then(({ data }) => {
            setLivros(data);
            console.log(data);
        })
    }, []);

Important to note that in the case of objects, arrays and functions the React will not compare each item or attribute, it will only compare the reference.


To Add a new item to the array, simply update the status by adding the new item.

  function addLivro() {
        api.post("/lista_livros", novo_livro)
           .then(() => setLivros(prevValue => [...prevValue, novo_livro]))
    }

In the above example the new item will be added only after the request is successfully completed.

Javascript - attribution by reference x attribution by value

Using Effect Hook (Effect Hook)

  • 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?

  • I believe you can update the status by adding the new item, I will add an example in the reply.

  • 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.

  • 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 the novo_livro as an example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.