Reputation: 4698
I'm using following code which produce "Possible unhandled promise rejection":
constructor(props){
super(props)
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)//successfully print data
this.setState({inventoryArray: items}).bind(this)//causing error
})
}
Though, following code runs successfully and prints response in log:
constructor(props){
super(props)
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)//Successfully print data
})
}
How to resolve this error?
Upvotes: 0
Views: 689
Reputation: 7424
You could also remove bind
and use arrow function so this
keeps the context in your component.
constructor(props) {
super(props)
DatabaseHandler.getInstance().getItems((items) => {
console.log(items)//successfully print data
this.setState({inventoryArray: items})
})
}
Also, your .bind(this)
is in the wrong place. It should be placed in the outer }
(where you close function
)
constructor(props) {
super(props)
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)
this.setState({inventoryArray: items})
}.bind(this)) // bind should come here
}
Making api requests in the constructor is a bad pattern though.
ReactJS Docs mentions that componentDidMount
is the recommended place to do so.
class YourComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
inventoryArray: [],
}
}
componentDidMount() {
DatabaseHandler.getInstance().getItems((items) => {
console.log(items)//successfully print data
this.setState({inventoryArray: items})
})
}
}
Upvotes: 1
Reputation: 1093
Typically, its a bad idea to make asynchronous calls in the constructor
of the component. Instead, I would recommend that you make these calls from the componentDidMount
as follows
class MyComponent extends React.Component {
componentDidMount() {
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)//Successfully print data
this.setState({ inventoryArray: items });
});
}
}
More about how to use the
constructor
in the official React docs
Upvotes: 2
Reputation: 4698
Making following changes solved this issue:
constructor(props) {
super(props)
this.onGetInventories = this.onGetInventories.bind(this)
//Loading inventory list from server
DatabaseHandler.getInstance().getItems(this.onGetInventories)
}
onGetInventories(items) {
console.log(items)
this.setState({inventoryArray: items})//Works
}
Upvotes: 0