Skip to content

React Native Updating State with this.setState

Hi I’m trying to update the state data value (data:[]) from API. the issue is from the line highlighted:

this.setState({data.datasets[0].data.data:response.data.rates.AUD})
import React from 'react'; import {Bar} from 'react-chartjs-2';
import axios from 'axios';
 
class App extends React.Component {
 
    constructor(props) {
       super(props)
       this.state = {
           data: {
               labels:["UK"],
               datasets:[
                 {label:"Dev Test",data:[]}
                ] }}
    
    this.test = this.test.bind(this) }  
    async test() {
        const response = await axios.get("https://api.exchangeratesapi.io/latest")
        this.setState({data.datasets[0].data[0]:response.data.rates.AUD})
    }

Answer

Hi please check below code.

this.setState((prev) => {
  prev.data.datasets[0].data[0] = response.data.rates.AUD;
  return {
    ...prev
  };
});