0

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

1 Answer 1

1

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>
   )
}
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry for the error: It should be this.state.dataSelection.map instead of this.state.dataSelection.data.map
Did you initialise state dataSelection to empty array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.