redux-form-submit-with-saga v0.0.3
#Why?
redux-form: "If your onSubmit function returns a promise, the submitting property will be set to true until the promise has been resolved or rejected. If it is rejected with an object like new SubmissionError({ field1: 'error', field2: 'error' }) then the submission errors will be added to each field (to the error prop) just like async validation errors are." (From "http://redux-form.com/6.1.1/docs/api/Props.md/")
redux-saga: When working with redux-saga, typically you dispath an unblocked action, then redux-saga catches the event, fork an independent "thread" to handle the action.
So how do you make your action return a promise?
#How to use it?
Assume "SAVA_DATA" is the action you want to dispatch when submitting the form.
##1. In your redux-saga:
import { submitFormSaga } from "redux-form-submit-with-saga";
export default function* root() {
yield fork(takeEvery, "SAVE_DATA", saveDataSaga);
yield fork(submitFormSaga);
}
function* saveDataSaga(form, data) {
const { response, error } = yield call(fetch...); //Your save data API.
if (error) {
yield put({ type: "SAVE_DATA_OK", target: form });
} else {
yield put({ type: "SAVE_DATA_FAIL", target: form });
}
}
##2. In your form:
import { submitFormSagaPromise } from "redux-form-submit-with-saga";
const FORM_NAME = "YOUR_UNIQUE_FORM_ID";
class SimpleForm extents React.Component {
const myOnSubmit = (data) => {
return submitFormSagaPromise(
dispatch, // This is your store.dispath from redux
{ type: "SAVE_DATA", target: props.form, data: data },
props.form,
["SAVA_DATA_OK", "SAVA_DATA_FAIL"] // The names should match the name in savaDataSaga
)
};
render() {
return (
<div>
<form onSubmit={props.handleSubmit(myOnSubmit)}>
<div>
<Field name="firstName" component="input" type="text" placeholder="First Name"/>
</div>
</form>
</div>
)
}
}
export default reduxForm({
form: 'UNIQUE_FORM_ID' // a unique identifier for this form
})(SimpleForm)
#Notes: 1. You can rename "SAVA_DATA", "SAVA_DATA_OK" and "SAVA_DATA_FAIL", as long as they match in your form and saga. 2. Why "target"? => To support submitting multiple different forms simultaneously.