Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

0

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

const getTableDataDetail = (value) => {
    setTtableDataDetail([ ...tableDataList, value ]);
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda