Arnold Starscream
Arnold Starscream

Reputation: 5

How to load response data using axios in react?

How to load response data using axios in react?

my componentdidmount:

var params = new URLSearchParams();
params.append('id', this.state.ids);

axios.post('http://127.0.0.1:8000/items/select/', params)
  .then(function(response, data){

    x => {

    let push = response.data.map((idb, index)=>{
        return(

          <SingleProduct takeid={idb} />    

            )
        })
    this.setState({dataSelection: push});
    }
  })

i want to create map response.data

Upvotes: 0

Views: 2443

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282160

Few things you need to take care of

First: bind the axios callback method, so that this inside it refers to the React component context

Second: Save the response in state rather than the component map

Third: Map over the state in render

state = {
    dataSelection: []
}
componentDidMount() {
  var params = new URLSearchParams();
  params.append('id', this.state.ids);

  axios.post('http://127.0.0.1:8000/items/select/', params)
    .then((response, data) => {
        this.setState({dataSelection: response.data});
      }
    })
}

render () {
   return (
      <div>
        {this.state.dataSelection.map((idb, index)=>{
          return(
               <SingleProduct takeid={idb} />    
            )
          })
        }
      </div>
   )
}

Upvotes: 1

Related Questions