0
votes

I had a component using classBased react, and it was working fine, I decided to switch to usestate and it stopepd working. Now the handlechange records the state in a random manner, but it doesnt work properly

My handlechange and the useState

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

const handleChange = (evt) => {
    const target = evt.target;
    const value = target.value;
    const name = target.name;
    console.log(name)
    console.log(value)
    setState({
        [name]: value
    });
}

My handlesubmit (it detects random values in that console.log, icant find the logic, but the log wont get both values as per inputed in the handlechange)

const handleSubmit = (event) => {
        event.preventDefault();

        const { email, password } = state;
        console.log(state)
        props.login(email, password, "login").
            then(data => {
            }).catch((err) => {
                if (err == "Error: Request failed with status code 403") {
                    setState({
                        wrongCombo: true
                    }, () => {

                    })
                } else if (err == "Network error") {
                    setState({
                        serverError: true
                    })
                }
            })
    }

And this is my render

<div>
            <form>
                {state.wrongCombo ? <Alert variant="danger" dismissible onClose={handleDismiss}> Wrong email and password combination </Alert> : null}
                {state.serverError ? <Alert variant="danger" dismissible onClose={handleDismiss}> Server Error </Alert> : null}
                <div class="form-group">
                    <label for="exampleInputEmail1">Email address</label>
                    <input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" onChange={handleChange} />
                </div>
                <div class="form-group">
                    <label for="exampleInputPassword1">Password</label>
                    <input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password" onChange={handleChange} />
                </div>
                <div className="text-center buttonContainer">
                    <button type="submit" class="btn btn-primary buttonLogin" onClick={handleSubmit}>Submit</button>
                </div>
            </form>
        </div>
1

1 Answers

5
votes

From the docs on useState:

unlike this.setState in a class, updating a state variable always replaces it instead of merging it.

You must replace all values in a useState object when updating them. You are only providing an object to the updater with one of the keys, so only that key will be retained.

A simple pattern for doing this would be to spread the previous state before passing your update:

setState(prev => ({...prev, [newKey]: newVal }));