Created
February 22, 2019 04:03
-
-
Save Dman757/4489ebcb883d77a3c5688a2a62480365 to your computer and use it in GitHub Desktop.
Async Submit Validation Formik + Redux-Thunk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*** The formik onSubmit ***/ | |
onSubmit={(values, actions) => { | |
createMember(values, token) | |
.then(res => { | |
console.log(res); // 'success' | |
// Change route or something | |
}) | |
.catch(err => { | |
console.log(err); // 'failure' | |
actions.setSubmitting(false); | |
}); | |
}} | |
// The button disabled when submitting | |
submitButton={isSubmitting => ( | |
<button disabled={isSubmitting}>Add Member</button> | |
)} | |
/*** THE ACTION DEFINITON ***/ | |
export const createMember = (data) => dispatch => { | |
dispatch({ type: actionTypes.CREATING_MEMBER }); // sets isCreatingMember true | |
return model | |
.post(data) | |
.then(data => { | |
dispatch(createdMember(data)); | |
return Promise.resolve('success'); // Return a resolved promise | |
}) | |
.catch(err => { | |
dispatch(createMemberFailure(err)); | |
return Promise.reject('failure'); // Return rejected promise, might return error message | |
}); | |
}; | |
export const createdMember = member => dispatch => { | |
console.log('created member', member); | |
dispatch({ type: actionTypes.CREATED_MEMBER /*member: ...member*/ }); // Store the member | |
}; | |
export const createMemberFailure = err => dispatch => { | |
console.error('oops', err); | |
dispatch({ type: actionTypes.CREATE_MEMBER_FAILURE }); // Set an error flag or message. | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment