Search code examples
reactjsreact-hooksfrontendreact-propsreact-state-management

Hook managed state on Form does not update in parent component


I have a form:

                        <FieldLabel label='Label'>
                            <Textfield
                                value={formState.name}
                                onChange={name => setFormState({ ...formState, name })}
                                name="someName"/>
                        </FieldLabel>
                        <FieldLabel label='Description'>
                            <Textarea
                                value={formState.description}
                                onChange={description => setFormState({ ...formState, description}}
                                name="someDesc"/>
                        </FieldLabel>

This form is 'dumb' meaning it gets its formState from a parent and dispatches setFormState when input is changed. In the parent component it looks like:

            <MyForm
                formState={formState}
                setFormState={setFormState} />

where formState and setFormState are hooks:

const initialFormState: FormState = {
    name: '',
    description: '',
}

const [formState, setFormState] = useState<FormState>({ ...initialFormState });

However, the state does not change, nor am I able to write anything into the inputs on the Form. When I click submit the initial state is logged, and all the properties are empty strings, just like in the initialFormState.

If anyone needs more info I'd be happy to provide it. Thanks.

Adding a codesandbox link: https://codesandbox.io/s/admiring-haze-gsy59?file=/src/App.js


Solution

  • onChange on input does not emit the value, it emits an event.

    Replace with onChange={e => setFormState({ ...formState, name: e.target.value })}