Here is my code:
import { useState } from "react";
const Testing = () => {
const [testa, setTesta] = useState({ Nickname: "Testing" });
return (
<>
<button type="button" onClick={(e) => setTesta({})}>Add</button>
<input type="text" value={testa?.Nickname} onChange={e => setTesta({ Nickname: e.target.value })} />
<p>Output: {testa?.Nickname}</p>
</>
);
};
export default Testing;
When the page initially loads the textbox value and the text below it both reflect the correct Nickname value.
When I type into the textbox the Nickname is correctly updated in both places.
When I click the Add button to reassign the state to an empty object, the output correctly disappears, but the textbox value remains unchanged.
What causes the difference between the input value and the plain text in this case?
2
Answers
The issue is with your button’s onClick event. You’re setting the state
testa
to an empty object with noNickname
key. Try this instead:Also, not sure why you had to set it as an object. I would have set it to a string.
The issue with your code is that when
setTesta({})
is called, testa becomes an empty object, andtesta?.Nickname
becomesundefined
. React throws an error because the value prop of the element expects a string or undefined, but whenvalue={undefined}
, the input’s displayed value doesn’t update as expected. The right code would be: