score:1

Accepted answer

unlike setting the state in a class component, usestate doesn't merge the object you pass, and you have to do it manually when setting the state. when you set age, for example, you replace the entire state object, which makes name to be undefined, and vice versa.

use functional update, and create a new state based on the previous state object before setting it.

const { usestate } = react

const adduser = () => {
  const initialuserstate = {
      id: null,
      name: '',
      age: 0
  }

  const [users, setusers] = usestate(initialuserstate)

  const handlechange = (e) => {
      // create the new state and set it
      setusers(prev => ({ ...prev, [e.target.name]: e.target.value }))

      e.preventdefault()
  }    

  return (
      <div>
          <input name="name" type="text" value={users.name} onchange={handlechange}/>
          <input name="age" type="number" value={users.age} onchange={handlechange}/>
      </div>
  )
}

reactdom.render(
  <adduser />,
  root
)
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

score:3

this page and this paragraph can help you understand the problem.

when you get the updated input through the onchange event listener you don't need to pass again the data through the value attribute.

when data is passed through the value attribute the component is considered "controlled". this means that the component is controlled by your code and shouldn't receive user input.

if you just want to set a default value you can use the defaultvalue attribute.

to remove the warning just remove the value={/* something */}.


Related Query

More Query from same tag