0

I'm getting this error as soon as I input a second character:

Uncaught TypeError: Cannot create property 'value' on string 'a'

The code so far:

function App() {
  const [object, setObject] = useState({
    name: "",
    value: "",
  });

  const handleChange = (e) => {
    setObject((object) => (object.value = e.target.value));
    console.log(object);
  };

  return (
    <div>
      <input type="text" onChange={handleChange} placeholder="Type something" />
    </div>
  );
}
Anushka Chauhan
  • 349
  • 3
  • 10

1 Answers1

1

This error occurs because the setState function is not being handled properly here.

Unlike the setState method found in class components, useState does not automatically merge update objects.


So we can say that the real question is:

How to change a single property of a state object using useState hook?

Solution 1: You can return a new object by spreading over previous state.

  const handleChange = (e) => {
    setObject((prevObject) => ({ ...prevObject, value: e.target.value }));
    console.log(object);
  };

Solution 2: You can create a new state object and completely replace the old one.

In this solution, you cannot guarantee that object has been refreshed to the latest version. Also, even if it were, you're setting object to be the same object reference it currently holds, therefore it will not be recognised as a change and the value will not be set.

  const handleChange = (e) => {
    const temp = object;
    temp["value"] = e.target.value;
    setObject(temp);
    console.log(object);
  };

See these questions:

  1. Updating and merging state object using React useState() hook
  2. Cannot create property on string
Anushka Chauhan
  • 349
  • 3
  • 10
  • 1
    Actually, solution 2 simply doesn't work. In that solution, you cannot guarantee that `object` has been refreshed to the latest version. Also, even if it were, you're setting `object` to be the same object reference it currently holds, therefore it will not be recognised as a change and the value will not be set. You should never update a state object in this way. Solution 1 is the correct solution though, so just go with that. – Software Engineer Oct 28 '22 at 21:40