reactjsreact-hookscontrolled-component

How to dynamically update the value for any input field with one event handler function, using hooks


TL;DR

Is there any way to dynamically update the value for input fields with one event handler function like we could do with stateful component.

I am working on a login form with 2 fields. Email and Password. When i am using 2 useState representing the two field, then when i update the state with handleChange both state get updated. Which is not the intention.

   const [email, setEmail] = useState()
   const [password, setPassword] = useState()

    const handleChange = e => {
        const {value} = e.target
        setEmail(value)
        setPassword(value)
    }

I don't want to use multiple event handler for handling each input field. I tried this

    const [state , setState] = useState({
        email : "",
        password : ""
    })

    const handleChange = e => {
        const {name , value} = e.target
        setState({
            [name] : value
        })
    }

But this updates one property at a time. And the other property value get lost. So is there any way that i can update all my input fields with one event handler function like we could do with stateful component.

    this.state = {
      email : "",
      password : ""
    }

    const handleChange = e => {
        const {name , value} = e.target
        this.setState({
           [name] : value
        })
    }

Solution

  • You should use setState with callback function:

    setState(prev => ({ 
        ...prev,
        email: 'new mail',
    }))
    

    You'll create a new state object, which was created by previous state. And you can override anything you need. You'd need more new objects if you'd have a complex state object.