Search code examples
javascriptreactjsdexie

Reactjs delete an item from Dexie.js


This example uses Reactjs and Dexie.js. I have a CRUD app without the D, which I presently require. While you can enter and store new items into the database, I am not sure how to select each item that has been added and delete them. I understand that you have to select them through their ID.

With the i tag I have attached a .onClick={this.removal}. However, I am unsure what to add to the removal function.

 var datastored = new Dexie('MyPlace');
datastored.version(1).stores({entries:'++id, title, entry' });
datastored.open().catch(function(err){alert("Could not open database:"+err)});

var Dashboard = React.createClass({
 getInitialState:function(){
  return {results: [] }
  },

runcheck:function(){
  let arr = [];
  datastored.entries
  .each((uploaded)=>arr.push(uploaded))
  .then(()=>this.setState({results:arr}));    
},   

componentDidMount:function(){
  this.runcheck();
},

removal:function(){
  datastored.entries.delete();    
},    

sendthru:function(){
  var newInput = {
  title: this.inputTitle.value,
  entry: this.inputEntry.value    
  };
  datastored.entries.add(newInput).then(()=>this.runcheck());   
  this.inputTitle.value = '';    
  this.inputEntry.value = '';     
},

renderdem:function(){
   var list = this.state.results.map(result =>{
    return <tr key={result.id}>
        <td>{result.id}</td> 
        <td>{result.title}</td> 
        <td>{result.entry}
        <i className="fa fa-times-circle exout" aria-hidden="true" onClick={this.removal}></i>
        </td>
    </tr>
});       
return (<div>
    <p>Title</p>        
    <input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />
    <p>Entry</p>        
    <textarea id="inputentry" ref={el => this.inputEntry = el} className="form-control"></textarea>
<button className="btn btn-info" onClick={this.sendthru}>Add</button>        
        <table className="table table-bordered"><tbody>{list}</tbody></table>
</div>);   
},    

render:function(){
  return this.renderdem();}        
});

ReactDOM.render(<Dashboard />, document.getElementById('main'));

I have included my code in JSFiddle

https://jsfiddle.net/5uevnock/


Solution

  • As you noticed you need to pass id in order to know what to remove. However, you cannot delete the entry immediately when binding the removal function to onClick. The trick here is to make removal return a function that will get called when on click happens.

    removal:function(id){
      var component = this;
      return function(evt) {
        datastored.entries.delete(id);   
        component.runcheck();
      }
    }
    

    Use it like this:

    <i className="fa fa-times-circle exout" aria-hidden="true" onClick={this.removal(result.id)}></i>
    

    Working example: https://jsfiddle.net/LukaszWiktor/u1vfoqgp/