I believe its quite simple but I am not able to figureout how to replace entire object using useState and setState. Here I have the empty data:
const emptyData = {
"foos": {},
"bars": {}
};
const [chartData, setChartData] = useState(emptyData);
I successfully get JSON response (response_json) from my API call which looks like below:
{
"foos": {
"foo1": {
"id": "foo1",
"foo_position": {
"pos_x": 300,
"pos_y": 100
},
},
"foo2": {
"id": "foo2",
"foo_position": {
"pos_x": 300,
"pos_y": 300
},
},
"foo3": {
"id": "foo3",
"foo_position": {
"pos_x": 300,
"pos_y": 500
},
}
},
"bars": {
"bar1": {
"id": "bar1"
},
"bar2": {
"id": "bar2"
}
}
}
Now I want to replace entire chart data or foos and bars which doesnt seem not to happen:
useEffect(() => {
async function handlePageLoad() {
const apiURL = getDataUrl(id);
const response = await getData(apiURL);
if (response.status === 200) {
const response_json = await response.json();
setChartData(response_json);
alert(JSON.stringify(chartData));
}
}
handlePageLoad();
}, []);
I also tried but no success:
setChartData({ ...chartData, foos: response_json.foos});
Edit: I put an alert to see if the data has been changed or not but I see following in the alert message which is similar to the initial data:
{"foos":{},"bars":{}}
Any help is much appreciated