Home > front end >  useState is not updating the state in React
useState is not updating the state in React

Time:05-22

ChangeHandler updates the state fine.

However, updating the state of id on onSubmit does not seem to update the id.

Code is:

import { useState } from "react"

export default function Form(props) {
    const [userInput, setUserInput] = useState({
        name: "",
        url: "",
        id: ""
    })

    const ChangeHandler = (e) => {
        const { name, value } = e.target

        setUserInput((prevState) => {
            return {
                ...prevState,
                [name]: value
            }
        })
    }

    const clearForm = () => {
        setUserInput({
            name: "",
            url: "",
            id: ""
        })
    }

    const onSubmit = (e) => {
        e.preventDefault()

        setUserInput(prevState => {
            return {
                ...prevState,
                id: Math.floor(Math.random() * 100) 
            } //does not work?
        });

        props.onFormData(userInput)
        clearForm()
    }

    return (
        <div>
            <form onSubmit={onSubmit}>
                <input name="name" className="input" type="text" value={userInput.name} placeholder="Name" onChange={ChangeHandler}></input>
                <input name="url" className="input" type="text" value={userInput.url} placeholder="url" onChange={ChangeHandler}></input>
                <button type="submit" className="button is-primary" >Send</button>
            </form>
        </div>
    )
}

CodePudding user response:

Try to keep order, set new id after form clear.

 const onSubmit = (e) => {
    e.preventDefault();

    clearForm();
    setUserInput(prevState => {
        return {
            ...prevState,
            id: Math.floor(Math.random() * 100) 
        }
    });

    props.onFormData(userInput);
}

CodePudding user response:

You don't need to use setUserInput. Just sand parms like this:

props.onFormData({
  ...userInput,
  id: Math.floor(Math.random() * 100)
})

When use change state, the state will applies on next render. That's why you can't use updated state.

  • Related