How to run code on a form submission
This guide shows you how to act on a step submission. Pass your callbacks to useStep()
in React, or to getStep() in Svelte.
What the SDK does on submit
- It collects the field values from the HTML form.
- It runs each
onBeforeSubmitcallback, one after another. - It checks each required field and each validation rule.
- It commits the responses to the experience state.
- It fires
form_submit_successorform_submit_erroron the event bus. - It runs your
onSuccessoronErrorcallback. - It moves to the next step.
Change the data before it is stored
const { form } = useStep({
onBeforeSubmit: async (data) => ({
...data,
'email-address': String(data['email-address']).toLowerCase(),
}),
})<script lang="ts">
const { form } = getStep({
onBeforeSubmit: async (data) => ({
...data,
'email-address': String(data['email-address']).toLowerCase(),
}),
})
</script>Act on the outcome
const { form } = useStep({
onSuccess: ({ data }) => analytics.track('lead_captured', data),
onError: (errors) => console.error('Validation errors:', errors),
})<script lang="ts">
const { form } = getStep({
onSuccess: ({ data }) => analytics.track('lead_captured', data),
onError: (errors) => console.error('Validation errors:', errors),
})
</script>A callback belongs to the component that passes it, and the SDK releases it when that
component unmounts. An onSuccess callback that throws cannot stop the flow. The SDK
reports the failure as form_submit_callback_error.
Choose the next step yourself
Call stopNavigation() inside onSuccess, then move where you want:
const experience = useExperience()
const { form } = useStep({
onSuccess: ({ data, stopNavigation }) => {
stopNavigation()
if (data['plan-type'] === 'enterprise') {
experience.goToStepById('enterprise-contact')
} else {
experience.goToNextStep()
}
},
})<script lang="ts">
const experience = getExperience()
const { form } = getStep({
onSuccess: ({ data, stopNavigation }) => {
stopNavigation()
if (data['plan-type'] === 'enterprise') {
experience.goToStepById('enterprise-contact')
} else {
experience.goToNextStep()
}
},
})
</script>goToStepById() takes a step id. goToStepByKey() takes the key of the step. When no
step matches, the call does nothing.
Related
- How to render a step form.
- SDK steps — the
formobject.
