0

I use ReactJS and axios I try to GET data customer

React: 16.5.2
axios: 0.18.0

I have a class with constructor:

constructor(props) {
  super(props);
  this.state = {
    reactTable: reactTableData(),
    reactBootstrapTable: reactBootstrapTableData(),
    dataCustomer: customerData(),
};

method customerData() :

export function customerData(){
  // axios get  
  return axios.get("my/url")
  .then(res => {
    let data = res.data.data;
    console.log(data);
    return data
  })
  .catch(err => {
    console.log(err);
  })
}

when I am console.log(this.state); I got Promise data like this:

enter image description here

I still new with ReactJS and I hope you can help me,
thanks.

Kevin
  • 403
  • 9
  • 22
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – VLAZ Jan 14 '20 at 09:18
  • Either `await customerData()` or use Promises if you want an actual array. However, that would lead to the constructor being asynchronous which is usually a bad practice. You may want to leave the promises in and let the object interact with them as Promises. – VLAZ Jan 14 '20 at 09:20
  • state change won't be reflected on the component, Try to do ths api call in component lifecycle – Ajay Ghosh Jan 14 '20 at 09:21

3 Answers3

2

That's pretty much normal, because you return a promise from your customerData function. I'd solve your problem like this:

constructor(props) {
  super(props);
  this.state = {
    reactTable: reactTableData(),
    reactBootstrapTable: reactBootstrapTableData(),
    dataCustomer: [],
  }
  this.initCustomerData()
}

async initCustomerData() {
  this.setState({
    customerData: await customerData()
  })
}
0

Your customerData will return the Promise only which needs to be resolved. That promise is getting set in dataCustomer.

What you can do is, call the method customerData inside another method which can be triggered from constructor or any other lifecycle method. Resolve the promise and then call the setState method to set the desired value.

Nikhil Goyal
  • 1,945
  • 1
  • 9
  • 17
-1

constructor(props) {
  super(props);
  this.state = {
    reactTable: reactTableData(),
    reactBootstrapTable: reactBootstrapTableData(),
  };

  this.initCustomerData();
}

initCustomerData = () => {
  customerData().then((data) => {
   this.setState({ dataCustomer: data })
  });
}