Kevin
Kevin

Reputation: 443

Resolving Promise Array

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.

Upvotes: 0

Views: 89

Answers (3)

Stefan Solopa
Stefan Solopa

Reputation: 1


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

  this.initCustomerData();
}

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

Upvotes: -1

Ruslan Prytula
Ruslan Prytula

Reputation: 36

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()
  })
}

Upvotes: 2

Nikhil Goyal
Nikhil Goyal

Reputation: 1973

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.

Upvotes: 0

Related Questions