Home > Blockchain >  React: how to update an array in a usestate
React: how to update an array in a usestate

Time:05-17

I'm using axios to populate an array with useState.

When the page render in the first time, the array update. But when I call the function after an edit, nothing happens.

    const [recursos, setRecursos] = useState([]);


const getRecursos = () => {
    Conexoes.Consultar(ma, password, "recurso").then(retorno => {
        console.log(retorno.Valores);
        setRecursos(retorno.Valores);
    })
        .catch(erro => {
            console.log(erro);
            alert("Erro Catch")
        }
        )
}

the function "Conexoes.Consultar" is a promise:

export const Consultar = (ma, password, tabela) => {
return new Promise((resolve, reject) => {
    const chamada = {
        ma: ma,
        s: password,
        Banco: vars.dbase,
        Tabela: tabela,
        Filtros:
        {
            id: "%%"
        }
    };
    axios.post(vars.servidor   'consultar/',
        chamada
    ).then((response) => {
        resolve(response.data);
    }, (erro) => {
        reject(erro);
    });

})

}

function that is called after edition: (the 'getRecursos()' is called, but nothing happens with the list )

    const salvarEdicao = () => {
    if (titleEditar == "Editar Recurso") {
        Conexoes.Atualizar(ma, password, "recurso", { id: idEditar }, { nome: valorEditar, ativo: ativo }).then(retorno => {
            getRecursos();
            setMenuEditar(false);
        }).catch(erro => {
            console.log(erro);
            alert("Erro Catch")
        });
    }
}

the function 'Atualizar' is a promise:

export const Atualizar = (ma, password, tabela, Filtros, Valores) => {
return new Promise((resolve, reject) => {
    const command = JSON.stringify({
        ma: ma,
        s: password,
        Banco: vars.dbase,
        Tabela: tabela,
        Filtros: Filtros,
        Valores: Valores
    });
    console.log(command);
    axios.post(vars.servidor   'atualizar/',
        command, { headers: { "Content-Type": "application/json" } }
    ).then((response) => {
        console.log(response.data);
        resolve(response.data);
    }, (erro) => {
        reject(erro);
    });

})

}

The array mapping:

 {recursos.length > 0 ? recursos.map((item, key) => {
                                        return (
                                            <tr key={key}>
                                                <td><CheckBox title={item.nome} checked={Conexoes.Bool(item.ativo)}></CheckBox></td>
                                                <td><Button title="Editar" onClick={e => {
                                                    setValorEditar(item.nome);
                                                    setAtivo(item.ativo);
                                                    setIdEditar(item.id);
                                                    setMenuEditar(true);
                                                    setTitleEditar("Editar Recurso");
                                                }
                                                }
                                                ></Button></td>
                                            </tr>
                                        );
                                    }) : <></>}

CodePudding user response:

First of all, any of the code you write should be in English.

In terms of the updating of the array, please try to:

setRecursos([...recursos, retorno.Values])

as you might be overwriting the previous values and only store the values from the latest response.

CodePudding user response:

You need to wait till your promise is resolved

const getRecursos = async () => {
    Conexoes.Consultar(ma, password, "recurso").then(retorno => {
        console.log(retorno.Valores);
        setRecursos(retorno.Valores);
    })
        .catch(erro => {
            console.log(erro);
            alert("Erro Catch")
        }
        )
}

// use the async function like this
const recursos = await getRecursos();

Same story for salvarEdicao, Atualizar... Please check more about async/await

  • Related