Updating state within React Hook Form

Viewed 963

I have a very simple submit form that I'm using React-hook-form to implement and I'm running into this strange issue where the global state isn't updated when I submit the first time, but it works the second time. Here's my code:

export default function Enter() {
    const { register, handleSubmit, watch, formState: { errors } } = useForm();
    const { state, dispatch } = useContext(Store)

    const onSubmit = (data) => {

        console.log('sending user: ', data.username)
        dispatch({
            type: 'SET_PLAYER',
            payload: data.username
        })
        console.log('UPDATED CLIENT STATE: ', state)
    }

    return (
    <>
        <form onSubmit={handleSubmit(onSubmit)}>
            <p>Enter your name to join lobby</p>
            <input {...register("username", { required: true })} />
            {errors.exampleRequired && <span>This field is required</span>}
            <input type="submit" />
        </form>
    </>
    );
}

Here's a picture of how state appears to be lagging behind, essentially:

enter image description here

1 Answers

Dominik's comment was spot-on. Even though updates to state are synchronous, state updates in between function refreshes so you should use data within the function and if you need to do something after that updates, then use useEffect and wait for the state change.

Related