Home > OS >  React cannot read state object from axios after getting the response with then method
React cannot read state object from axios after getting the response with then method

Time:10-02

I have a react component that calls the backend when the page loads then update the internal page state based on the Json response I use axios for that so constructor is like :

constructor(props){
    super(props);
    this.state={elements:[]};
} 

then on componentDidMount:

componentDidMount(){
  axios.post('https://example.com/getElements').then(function(response){
    for(let i=0;i<10;i  ){
     this.state={[this.state.elements]: [...this.state.elements, response.data[i]['element'] ]};
}
}

so basically it fetches the response data which is a json object that has parents marked with numbers: 0 ,1 ,2 , etc.. until 10 Each of them has key and value so I have to presist each element from the json response to the react state object using a for loop the problem is that trying to modify state object from axios async 'then' method makes the state object unreadable (Cannot read properties of undefined reading state).

any solution for how to fix that ?

CodePudding user response:

To make an axios call and store the result, your code should look something like this:

axios.post(url).then(response => {
  this.setState(prevState => {
     return { /* combine response with prevState as needed */ }
  })
});
  • Related