Form – onSubmit hold on to initial state of variable

Dear team,

When I try to access a variable from within onSubmit, it always returns initial state of the variable

Attached code demonstrate a very simple Gatsby+tina solution

onSubmit method on tina form and onClick method on “Say my name” button call the same method onSubmitImplementation which yells out current value of name

name starts as Jon and useEffect changes it to snow

When I click on Submit button on tina form I get Jon, the initial value

When I click on Say my name button, I get Snow, the latest value

What should I do in order to access current state of an object from onSubmit. Please note the object could be something like security context and may not necessarily be a part of from page-data

Many thanks in advance



I also tried

const [modifiedValues, form] = useForm(formConfig, { values: {name}, fields: formConfig.fields })


Just figured objects, variables send through second parameter of useForm are passed through to onSubmit, even if they are not a part of the main filed set. I could use values to patch through name, but would like to know whether is there a better way for onSubmit to get the current values

onSubmit receives the current form values, as in the form values that have been edited or updated and need to be saved.

I’m not sure exactly what you are trying to do with name but perhaps you could pass it in as a parameter to that onSubmitImplementation function. You can read more about handling stale state with React in this article.

Hello Kendall,

Many thanks for the reply. I will try the technique described in the article

I tried passing the name as a parameter to onSubmitImplementation and got pretty much the same result. I have updated the code to reflect the changes

name was just to keep the demo simple. It represents a security context required by an api used to save data. To make matters complicated, the context would be in an uninitialized state when the component is first rendered and only fully initialized after a second or so. useEffect was as a crude attempt to demonstrate delayed initialization

The issues seems to be onSubmit uses the initial state set on an object even after it been modified.

Ah I get your question now. Since name is not an editable form value (it is not passed as a field), you need to pass it as a watched value so the form knows to update when the value changes.

So your first instinct was correct in that you can pass it to watched values and reference in the onSubmit as The form state is separate from the components’ state where the form is defined, if that makes sense.

    onSubmit: (values) => {

Awesome … thanks for the clarification @kendall

1 Like