0

I have an array in the state and want to change the array depending on the index here is the method I use

dynamicFieldsOnChange(e, index) {
    this.setState({[product_colors[index]]: e.target.value});
};

But it's not working any idea why?

Kadiem Alqazzaz
  • 554
  • 1
  • 7
  • 22

2 Answers2

0

Directly updating state value using

this.state[e.target.id] = e.target.value 

is a bad practice. You should always avoid that.

Instead, you should do something like this,

this.setState({[e.target.id] : e.target.value});

This will set id in a local state.

prabin badyakar
  • 1,636
  • 2
  • 16
  • 24
0

You need to get the previous state first, using prevstate callback event. if you want to retain all the elements of an array . spread the prevState . then call the product_colors then pass the modified array.

Like this:

  dynamicFieldsOnChange(e,index)
  {
    this.setState( (prevState) => {
      prevState.product_colors[index] = e.target.value
      return{
        ...prevState,
        product_colors: [...prevState.product_colors]
      }
      });
  };  
Mervzs
  • 1,114
  • 7
  • 21
  • can you you give me the initial and final output of the state? to know what s the problem? – Mervzs Mar 23 '19 at 10:04
  • here is the array for example `product_colors: (2) ["white", "New Entry 1"]` I want to change `"New Entry 1"`, so I used `index` (which in this case equals 1) to change the entry – Kadiem Alqazzaz Mar 23 '19 at 10:07
  • I mean , what is the output and input of state, on implementing of the code above that i suggested. – Mervzs Mar 23 '19 at 10:09
  • error : `Uncaught TypeError: Cannot read property 'value' of null` – Kadiem Alqazzaz Mar 23 '19 at 10:10
  • your error here must be e.target.value, does not exist in the first place. check the e property in console log to get the proper address of the value you wanna get. try to make e.value.target to static value like. prevState.product_colors[index] = 'Change' to know that the logic is working – Mervzs Mar 23 '19 at 10:14