Search code examples
javascriptreactjsreact-state

React: Why does the value of my input not update, but outputting the same same state to the page or console does?


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.

screenshot of initial load

When I type into the textbox the Nickname is correctly updated in both places.

updated text

When I click the Add button to reassign the state to an empty object, the output correctly disappears, but the textbox value remains unchanged.

unchanged textbox value

What causes the difference between the input value and the plain text in this case?


Solution

  • The issue with your code is that when setTesta({}) is called, testa becomes an empty object, and testa?.Nickname becomes undefined. React throws an error because the value prop of the element expects a string or undefined, but when value={undefined}, the input’s displayed value doesn't update as expected. The right code would be:

    <input type="text"
        value={testa?.Nickname || ""} // Provide a fallback value
        onChange={e => setTesta({ Nickname: e.target.value })}
    />