I am trying to figure out how to set a react state to the value of the database. I am using Dexie.js.
var Duck = React.createClass({
getInitialState:function(){
return { century:'' }
},
fridge:function(){
var db = new Dexie('homie');
db.version(1).stores({
friends:'name, race'});
db.open().catch(function(){
alert("Open failed: ");
});
db.friends.put({name: 'Johnny', race:'hispanic'}).then(function(){
return db.friends.get('Johnny');
}).then(function(samba){
console.log(samba.race);
this.setState({century: samba.race});
});
},
render:function(){
return (<div>
<input type="submit" value="Submeet" onClick={this.fridge} />
<p>{this.state.century}</p>
</div>);
}
The fridge
function works, as it places the appropriate item in the database. The only part of the code that does not work is this.setState({century:samba.race})
. This leads to errors of Cannot read property 'setState' of undefined
.
How would I re-do the setState
to take in the data from my db?
The problem is not related to Dexie.js (nice indexDB wrapper btw). You invoke this.setState()
from a callback you pass to .then
as handler. When the callback is invoked inside the promise context this
is undefined
.
To solve that you need to explicitly set the this
of the callback, using .bind
or the old that = this
, or just use an arrow function (demo):
.then((samba) => {
console.log(samba.race);
this.setState({
century: samba.race
});
});