Classic problem - I want to validate a form before submitting it.
My submit button triggers an action (simple dispatch or thunk). If the form is valid, submit it - else, trigger an error message.
The simple solution: dispatch an action e.g. VALIDATE_AND_SUBMIT, which in the reducer will validate the form, and submit or set an error state.
I feel like these are two different actions: VALIDATE
{
type: "VALIDATE",
formData
}
This should validate and set errors.
{
type: "SUBMIT",
// get form data and errors from state
}
SUBMIT - should submit provided there's no error state.
Even if I use redux-thunk, I can't get feedback from the first VALIDATE action. Is my thought process anti-pattern here? How can I validate before submitting a form?
I think part of your issue is think of actions as something that is happening rather than something has caused the state to change.
"Validate" is not an action. "Validation failed" is the action.
"Submitting" the data is not an action. "Data was submitted" is the action.
So if you structure your thunk with that in mind, for example:
export const validateAndSubmit = () => {
return (dispatch, getState) => {
let formData = getState().formData
if (isValid(formData)) {
dispatch({type: "VALIDATION_PASSED"})
dispatch({type: "SUBMISSION_STARTED"})
submit(formData)
.then(() => dispatch({type: "SUBMITTED" /* additional data */}))
.catch((e) => dispatch({type: "SUBMISSION_FAILED", e}))
}
else {
dispatch({type: "VALIDATION_FAILED" /* additional data */})
}
}
}
I think part of your issue is think of actions as something that is happening rather than something has caused the state to change.
"Validate" is not an action. "Validation failed" is the action.
"Submitting" the data is not an action. "Data was submitted" is the action.
So if you structure your thunk with that in mind, for example:
export const validateAndSubmit = () => {
return (dispatch, getState) => {
let formData = getState().formData
if (isValid(formData)) {
dispatch({type: "VALIDATION_PASSED"})
dispatch({type: "SUBMISSION_STARTED"})
submit(formData)
.then(() => dispatch({type: "SUBMITTED" /* additional data */}))
.catch((e) => dispatch({type: "SUBMISSION_FAILED", e}))
}
else {
dispatch({type: "VALIDATION_FAILED" /* additional data */})
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With