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

82
Views
useState react hook with compliquated enumerable properties

I'm struggling to modify a JSON like object with the setState property (from a useState hook). I would like to add items to labels and data arrays, at the same time.

  const dataInit = {
    labels: [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
    ],
    datasets: [{
      label: 'My First dataset',
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      data: [0, 10, 5, 2, 2, 30, 49,80],
    }]
  };

Here is the initialization of my useState hook with a try that doesn't work:

const [graphData, setGraphData] = useState(dataInit)

setGraphData(prevState => ({
                       ...prevState,
                       labels: prevState.labels.concat(["hey"]),
                       datasets: prevState.datasets[0].data.concat([3])
                       })
             )

Thanks for helping

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Always return a new object to the nested props that are objects, while setting the state. What concat does is append new value to the existing object. Try something like:

const [graphData, setGraphData] = useState(dataInit)


setGraphData(prevState => 
{
    let _datasets  = [...prevState.datasets];
    _datasets[0].data = [..._datasets[0].data, ...data];
    return {
        ...prevState,
        labels: [...prevState.labels, "hey"], //new array returns with previous and new value
        datasets: _datasets
    }
})
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!