-1

I'd like to do someething like

class Example exports React.Component{
   state = {
       items = {},
       id = 0,
       template = {"id":0, "itemName":""}
   }
   addItem = (name) => {
       let item = {...this.state.template,"id":this.state.id,"itemName":name };
       this.setState({items["item0"]:{item}});
   }
   render()/*code*/
}

but i cant add a key to the dictionary using setState :c

Siegh
  • 161
  • 2
  • 5
  • 1
    Does this answer your question? [Correct modification of state arrays in ReactJS](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs) – Codebling Mar 13 '20 at 01:52

1 Answers1

1

Use the spread operator to include the existing items, then add your new item under its key:

setState({
  items: {
    ...items,
    “item0”: item
  }
}

If you need to compute the key you can use the computed property names bracket syntax:

const itemId = 'bananas';

setState({
  items: {
    ...items,
    [itemId]: item // equivalent of 'bananas': item
  }
}

Or use an array:

setState({
  items: [
    ...items,
    item
  ]
}
ray
  • 26,557
  • 5
  • 28
  • 27
  • is there a way that i can change the key depending on the id? like ` class Example exports React.Component{ state = { items = {}, id = 0, template = {"id":0, "itemName":""} } addItem = (name) => { let item = {...this.state.template,"id":this.state.id,"itemName":name }; this.setState({items[`item ${this.state.id}`]:{item}}); } render()/*code*/ } ` – Siegh Mar 13 '20 at 02:11
  • yes. use [computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) like `{ [someIdVar]: someValue }`. – ray Mar 13 '20 at 03:05
  • updated answer with computed property name example. – ray Mar 13 '20 at 03:24