Home > Blockchain >  How do I call an object inside useReducer?
How do I call an object inside useReducer?

Time:12-04

So I have a simple form with two inputs, and the idea is that when you fill in the form and click enter it shows you on the screen the info you typed in. I managed to do this with one input, but now when I want to try it with an object I'm getting the following error:

enter image description here

I'm relatively new to React and need some help with this. The link for codesandbox is:

https://codesandbox.io/s/learning-react-5vj5g?file=/src/MultipleInputs.js

CodePudding user response:

const [user, setUser] = useState({
  id: uuid(),
  name: "",
  age: ""
});

// ...

value={user.name}
onChange={(e) => setUser(e.target.value)}

user is starting off as an object, but then when the change event happens, you're setting the state to be a string. So before, user.name was an empty string, and afterwards it's undefined (because user is a string, and string don't have a .name property). Since it's changing from a string to undefined, react shows that warning.

Assuming you want it to stay an object, do something like this:

onChange={(e) => {
  const newName = e.target.value;
  setUser(prev => {
    return {
      ...prev,
      name: newName
    }
  });
}}

(and do a similar thing for the age input).

Another option is to use separate states for the name and age, instead of combining them:

const [person, dispatch] = useReducer(reducer, []);
const [name, setName] = useState('');
const [age, setAge] = useState('');
// ...
<input
  type="text"
  value={name}
  onChange={(e) => setName(e.target.value)}
/>

CodePudding user response:

You inccorect call serUser with e.target.value string. You must set object because user type object. Also you can optimize it with dynamic keys. Demo

const handleChange = (value, type) => {
    setUser((prev) => {
      return {
        ...prev,
        [type]: value
      };
    });
  };

JSX

 onChange={(e) => handleChange(e.target.value, "name")}
  • Related