Jason Chen Jason Chen - 2 months ago 19x
React JSX Question

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

. 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({
return {results:[
{id:'', name:'',age:''}

// 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');
friends: '++id, name, age'

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 = {
name: resname,
age: resage


// this is how you update the state of the object with new data
var newResults = this.state.results.slice(); // clone the array
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>;

return (
<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}/>


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

I have added it to JSFiddle.


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});