I have the following problem. The below code does not work as intended. The first log displays the correct value. e.g. "SomeName". But "SomeName" is not displayed in the inputName
text.
To make things more readable I simplified the function.
function EditAboutModal(props) {
const [show, setShow] = useState(false);
console.log(props.data.Name);
const [Name, setName] = useState(props.data.Name);
function handleNameChange(e) {
setName(e.target.value);
}
return (
<>
<div className="row mb-3">
<label htmlFor="inputName" className="col-sm-2 col-form-label">Name:</label>
<div className="col-sm-10">
<input type="text" className="form-control" id="inputName" value={Name} onChange={handleNameChange} />
</div>
</div>
</>
);
}
I expect the useState
to set the Name
variable to props.data.Name
.
The log correctly displays that a value exists for this variable, but no value is shown in the textfield and when I log the Name
variable it is shown as unknown.
It can be null
or something else in the first component render. Use useEffect
to handle this problem:
useEffect(() => {
setName(props.data.Name);
}, [props.data.Name]);