Reputation: 443
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:
I still new with ReactJS and I hope you can help me,
thanks.
Upvotes: 0
Views: 89
Reputation: 1
constructor(props) {
super(props);
this.state = {
reactTable: reactTableData(),
reactBootstrapTable: reactBootstrapTableData(),
};
this.initCustomerData();
}
initCustomerData = () => {
customerData().then((data) => {
this.setState({ dataCustomer: data })
});
}
Upvotes: -1
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
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