Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
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 answers
Answer question

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 Report

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 Report

0

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

const getTableDataDetail = (value) => {
    setTtableDataDetail([ ...tableDataList, value ]);
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!