Stack Overflow Asked by Ross Attrill on December 25, 2021
If I set a default value for an object using useState
in a React function component, then my control linking to a field in that object does not get updated state values for a field in the object.
See this example:
import React, {useState} from 'react'
import {Form} from 'react-bootstrap'
function BrokenForm(props) {
const defaultO = {
field1: "this gets stuck in state - or so it looks ..."
}
const [o, setO] = useState(defaultO) // Setting a default here causes trouble
const [x, setX] = useState('simple value') // This works as expected
const onChangeField1 = (event) => {
let newO = o
newO.field1 = event.target.value
setO(newO)
}
const onChangeX = (event) => setX(event.target.value)
return (
<Form>
<Form.Label>Object Field1</Form.Label>
<Form.Control value={o.field1} onChange={onChangeField1} />
<Form.Label>Simple Value</Form.Label>
<Form.Control value={x} onChange={onChangeX} />
</Form>
)
}
The first form control never updates with the value of o.field1
even though the onChangeField1
function looks like it has updated it.
However, if I initialize the value of o
with a null object, everything works fine:
const [o, setO] = useState[{}]
What am I doing wrong?
Hi there in onChangeField1 you are not immutably cloning the state and that could be one of the reasons for the issue.When you assign an object to another in js it gives it a reference so
let newO=o;
It is just passing a reference
What you should do instead is
let newO={...o}
This will immutably clone the state.
Let me know if you face any issues even after this,
Answered by Yash.S.Narang on December 25, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP