user10491490
user10491490

Reputation: 31

React Material UI TextField value is not updating

There are four files: createPollForm.js, formOptions.js, optionList.js, and option.js

createPollForm has a state of option array with initial value:

const [options, setOptions] = useState([{
        id: uuidv4(),
        value: ""
    }]);

const handleOptionsChange = value => {
       setOptions(value);
}

return(
        <FormOptions 
               options={options}
               handleOptionsChange={handleOptionsChange}
        />
)

formOptions.js receives handleOptionsChange from createPollForm.js :

const handleValue = id => {
      const result = options.filter(option => option.id === id)
      return result[0].value
}

const handleChangeValue = (e, id) => {
      options.forEach(option => {
          if(option.id === id){
              option.value = e.target.value
          }
      })

      handleOptionsChange(options)
}

return (
     <OptionList 
            options={options}
            handleValue={handleValue}
            handleChangeValue={handleChangeValue}
     />
)

optionList.js contains all the option TextFields

return (
        <div>
            {options.map(option => (
                <Option 
                    key={option.id} 
                    id={option.id}
                    handleValue={handleValue}
                    handleChangeValue={handleChangeValue}
                />
            ))}
        </div>
    )

option.js:

return(
       <TextField 
           label="Option"
           value={props.handleValue(props.id)}
           onChange={e => props.handleChangeValue(e, props.id)}
       />
    )

Before adding the value in TextField in option.js, everything works fine, however, after adding the value with the handleValue function for assigning value to each option TextField, the TextField will just remain blank when I am typing in the corresponding TextField even though I can see the value of option array state is updated through console.log. Therefore, I assume for some reason the TextField has trouble to read the most updated value from option array.

Could anyone help me with this? I just started learning reactjs, any help would be greatly appreciated.

Upvotes: 3

Views: 4762

Answers (1)

pl2ern4
pl2ern4

Reputation: 375

In handleOptionsChange method in createPollForm.js. update state like given:

setOptions({...options,value})

because initial value is object, and you passing value.

Upvotes: 3

Related Questions