简体   繁体   中英

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

I have the below structure:

在此处输入图像描述

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:

在此处输入图像描述

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

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]
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM