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

189
Views
How to concatenate a new item with hooks in react js?

I have the below structure:

enter image description here

What I'm trying to do is to update the metrics with new data:

  const [data, setData] = useState<any>({});
  getServerResourceUsage(serverId, intervalTime)
    .then(res => {
      setData((state: any) => ({
        ...res.data.data,
        metrics: {
          time_series: state.metrics.time_series.concat(res.data.data.metrics.time_series)
        }
      }));
    })
    .catch(error => {
      console.log(error.response)
    })
    .finally(() => {
      setLoading(false);
    });

Now what I get is the below error:

enter image description here

I'm struggling to find out why state is empty and how can I even console log its value to debug the issue.

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

0

Change the way you declare state, so it's not gives you an error in the first fetch.

const [data, setData] = useState<any>({
    metrics: {
        time_series: []
    }
});

And setState parameter is should be a new data instead a callback.

setData({
  ...res.data.data,
  metrics: {
    time_series: data.metrics.time_series.concat(res.data.data.metrics.time_series)
  }
});

Or you can spread existing time_series too:

setData({
  ...res.data.data,
  metrics: {
    time_series: [...data.metrics.time_series, ...res.data.data.metrics.time_series]
  }
});
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!