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

207
Visualizações
How to store a value in an array without deleting the previous value

I have this method:

const [tableDataList, setTableDataList] = useState([]);

const getTableDataDetail = (value) => {
    let dataDetail = tableDataList;
    dataDetail = [...dataDetail, ...value]

    setTtableDataDetail(dataDetail);
};

This method is called every time I click a button But I want to keep the previous value and add the new value to the previous one..But what I have is that every time I click, the previous value is deleted.What should I do?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

There are two scenarios.

If "value" is number then,

let dataDetail = [...tableDataList, value]

If "value" is array then,

let dataDetail = [...tableDataList, ...value]

The below code is worked for me.

For number:

const [tableDataList, setTableDataList] = React.useState([]);

const getTableDataDetail = (value) => {
let dataDetail = [...tableDataList, value]
setTableDataList(dataDetail);
};

<button onClick={() => getTableDataDetail(1)}>Click</button>

For Array:

const [tableDataList, setTableDataList] = React.useState([]);

const getTableDataDetail = (value) => {
let dataDetail = [...tableDataList, ...value]
setTableDataList(dataDetail);
};

<button onClick={() => getTableDataDetail([1,1])}>Click</button>
about 4 years ago · Juan Pablo Isaza Relatório

0

You can make a shallow copy of the state and then add new item to it:

const [tableDataList, setTableDataList] = useState([]);

const getTableDataDetail = (value) => {
    let copy = [...tableDataList];
    copy.push(value)
    setTtableDataDetail(copy);
};
about 4 years ago · Juan Pablo Isaza Relatório

0

const [tableDataList, setTableDataList] = useState([]);

const getTableDataDetail = (value) => {
    setTtableDataDetail([ ...tableDataList, value ]);
};
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