1
votes

I have a page where i fetch data from server and setting value in state for controlled inputs. (e.g I have input which has value of this.state.name, i fetch name from server for example Dave and set it in state as name, so value of input is Dave. it works but i got problem with array of objects

so this is the state

this.state = {
        ingredients: [{ ingredient: "", quantity: '' }],
        //other properties
   }

and this is how i use ingredients

{this.state.ingredients.map(({ ingredient, quantity }, index) => (


   <div key={index}>
        ingredient: <input value={ingredient} className="ingredientClass" type="text" autoComplete="off" placeholder="e.g: pepper" onChange={{e => this.update(index, "ingredient", e.target.value)} />
        quantity: <input value={quantity} autoComplete="off" type="text" placeholder="e.g: 1g" onChange={e => this.update(index, "quantity", e.target.value)} />
        <button onClick={this.BtnClick}>delete</button> <br />
       {this.state.errorFor === 'ingredientsfield' ? this.state.errmsg : null}
   </div>
))}

But this causes this error:

Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: link

Why is that happening? How can I fix it?

P.S: i checked and ingredients are succesfully fetched from server

UPDATE: code of onChange event

update(index, key, value) {
    this.setState(({ ingredients }) => ({ ingredients: ingredients.map((ing, i) => i === index ? { ...ing, [key]: value } : ing) }));
    console.log(this.state.ingredients)
}
1
What is the initial value of ingredients before you fetch it?Cool Guy
strings... why does it matter?iLiA

1 Answers

5
votes

The problem is that one of inputs has undefined or null value at some moment.

I can't understand what changes your input value to null (undefined) from the code you show. But you can use ReactDevTools to observe the value of the input during your application running.