Search code examples
javascriptreactjsdexie

Assigning a unique key id using React and Dexie?


The code below lacks a proper key prop. I am using Dexie.js for this example.

Basically, I have an auto-incrementing key with ++id. Now, I would like to make sure that my var newFriend auto-increments this, but I am unsure of how to properly designate it. It is meant to be used in a li key={result.id}.

The resulting error is child keys must be unique; when two children share a key, only the first child will be used.

I would like to set var newFriend to auto-increment my id.

Don't mind the comment tags. They are hot off a previous question of mine.

var SisterChristian = React.createClass({
  getInitialState:function(){
    return {results:[
      {id:'', name:'',age:''}
    ]}
  },

  zanzibar:function(){
    // don't use document.querySelector(), you should be able to access any of your DOM elements like this
    var resname = this.inputNameEl.value;
    var resage = this.inputAgeEl.value;
    var datastoring = new Dexie('MySpace');
    datastoring.version(1).stores({
      friends: '++id, name, age'
    });

    datastoring.open().catch(function(err){
      alert('Oh no son:' +err);
    });

    // you can't do this, you need to add a new item to the results array, not reset the array
    // datastoring.friends.each((friend)=>{
    //   this.setState({results:[{name:resname, age:resage}] });
    // }); 

    var newFriend = {
      id:,
      name: resname, 
      age: resage
    };

    datastoring.friends.add(newFriend);

    // this is how you update the state of the object with new data
    var newResults = this.state.results.slice(); // clone the array
    newResults.push(newFriend);
    this.setState({results: newResults});
  },

  renderResults:function(results) {
    return results.map(result => { // this is how you create DOM elements from an array of objects
      return <li key={result.id}>{result.name}, {result.age}</li>;
    });
  },

  render:function(){
    return (
      <div>
        <input type="text" id="inputname" ref={el => this.inputNameEl = el} />
        <input type="text" id="inputage" ref={el => this.inputAgeEl = el} />
        <input type="submit" value="Shipping And Handling" onClick={this.zanzibar}/>
        <ul>{this.renderResults(this.state.results)}</ul>
      </div>
    );
  }

});

ReactDOM.render(<SisterChristian/>, document.getElementById('bacon'));

I have added it to JSFiddle. https://jsfiddle.net/7xet1nv0/1/


Solution

  • Dexie generates a unique id for each item automatically (the '++id' in the schema). Dexie returns a promise after each .add() action. When the promise is fulfilled, you can retrieve the unique id that Dexie assigned, and use it (demo):

    datastoring.friends.add(newFriend).then((id) => {
          // this is how you update the state of the object with new data
            var newResults = this.state.results.concat([Object.assign({}, newFriend, { id })]); // add the id to the newFriend object, and then concat it to the all state to get a new array
            this.setState({results: newResults});
        });