Hi I’m trying to update the state data value (data:[]
) from API. the issue is from the line highlighted:
JavaScript
x
2
1
this.setState({data.datasets[0].data.data:response.data.rates.AUD})
2
JavaScript
1
21
21
1
import React from 'react'; import {Bar} from 'react-chartjs-2';
2
import axios from 'axios';
3
4
class App extends React.Component {
5
6
constructor(props) {
7
super(props)
8
this.state = {
9
data: {
10
labels:["UK"],
11
datasets:[
12
{label:"Dev Test",data:[]}
13
] }}
14
15
this.test = this.test.bind(this) }
16
async test() {
17
const response = await axios.get("https://api.exchangeratesapi.io/latest")
18
this.setState({data.datasets[0].data[0]:response.data.rates.AUD})
19
}
20
21
Advertisement
Answer
Hi please check below code.
JavaScript
1
7
1
this.setState((prev) => {
2
prev.data.datasets[0].data[0] = response.data.rates.AUD;
3
return {
4
prev
5
};
6
});
7