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.