简体   繁体   中英

when i fill a form input it shows the previous value in console log

when i fill a form input it shows me previous value eg if i type 1 it shows "" and after that if i type 2 then it shows "1" and soo on like its showing the value of previous state. i cant figure out how to fix it. Any help is appreciated thanks

const Create = () => {

let history = useHistory();

let [person, setPerson] = useState({
    name:"",
    about:"",
    email:"",
    image:"",
})

let createPerson = async () => {
    fetch(`/api/person-create/`, {
        method: "POST",
        headers: {
            "content-type": 'application/json'
        },
        body: JSON.stringify(person)
    })
}

let handleChange = (e) => {
    setPerson({...person, [e.target.id]: e.target.value})
    console.log(person)
}

return (
    
    <form>
        <div>
            <h2 className="notes-title" style={{marginLeft:'700px'}}>
                <button onClick={() => history.push('/')} className="btn btn-primary mt-4">
                    &#10094; Back
                </button>
            </h2>


            <h2 className="mt-4 mb-4" style={{width: '600px', marginLeft:'700px'}}>
                New Person
            </h2>

            <div className="form-group" style={{width: '600px', marginLeft:'700px'}}>
                <label>Name</label>
                <input onChange={handleChange} className="form-control" id="name" placeholder="Enter Name" value={person.name} />
            </div>

            <div className="form-group" style={{width: '600px', marginLeft:'700px'}}>
                <label for="exampleInputEmail1">About</label>
                <textarea style={{height: '250px'}} className="form-control" id="about" placeholder="Tell us somthing about yourself" value={person.about} />
            </div>

            <div className="form-group" style={{width: '600px', marginLeft:'700px'}}>
                <label>Email</label>
                <input className="form-control" id="email" placeholder="Enter Email" value={person.email} />
            </div>

            <div className="custom-file mt-3" style={{marginLeft:'700px'}}>
                <input type="file" className="custom-file-input" id="image" value={person.image} />
                <label className="custom-file-label" for="customFile">Choose file</label>
            </div>
            
            <button type="submit"  style={{marginLeft:'700px'}} className="btn btn-primary mt-4">Submit</button>

        </div>
    </form>

    )
}

export default Create

i get that its happening because the state only updates once i put somthing inside the form but cant figure out a fix.

setPerson asyncronous function, you must check person update in useEffect . Docs

useEffect(() => {
    console.log("correct", person);
  }, [person]);

Demo

Better you use Previous State when you update your state. Please follow the below code:

let handleChange = (e) => {
    setPerson( (per) => ({...per, [e.target.id]: e.target.value}));
    console.log(person)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM