Calling an async redux action creator on form submission

和自甴很熟 提交于 2021-02-11 06:36:26

问题


In a typical React/Redux app it's pretty common to use redux-thunk and async action creators to trigger an AJAX request and dispatch actions on start/success/failure of this request.

However, I can't find a way to integrate such a function with react-final-form. Its redux submission example is using react-redux-promise-listener which dispatches an action immediately, but does not let me call my async action creator.

It is possible to integrate react-final-form with a redux app that uses an async action creator to perform the on-submit action? I would prefer not having to move my AJAX logic into the reducers.


回答1:


All the form library cares about is that the onSubmit function returns a Promise. If dispatching your action created with your custom action creator can return a promise (perhaps via some middleware?), that’s all that React Final Form cares about. The promise listener library is more for side-effect middlewares, like Redux Saga.




回答2:


Check this solution:

My Component:

export function submitEdit(dataPath: string, payload: ActionWithCallback<number>): ActionWithDataPathBase<ActionWithCallback<number>> {
return {
    type: constants.EDIT_SUBMIT,
    dataPath,
    payload
};

}

Action:

export function submitEdit(dataPath: string, payload: ActionWithCallback<number>): ActionWithDataPathBase<ActionWithCallback<number>> {
return {
    type: constants.EDIT_SUBMIT,
    dataPath,
    payload
};

}

ActionWithCallBack:

export interface ActionWithCallback<T> {
data: T,
callback?: ((errors?: SubmissionErrors | undefined) => void)

}

the saga:

function* update(action: ActionWithDataPathBase<ActionWithCallback<number>>) {
try {
    const formData: PeopleForUpdateModel = yield select((state: AppState) => get(state.forms, action.dataPath));
    yield call(ajax.put, `/people/${action.payload.data}`, formData);
}
catch (error) {
    if (action.payload.callback) {
        const errors = handleFormErrors(error.response);
        yield call(action.payload.callback, errors);
    }
}
finally {
    yield put(actions.changeValue("edit.isLoading", false));
}

}

The HandleFormErrors function parses my server response to accepted final form errors format SubmissionErrors



来源:https://stackoverflow.com/questions/51101038/calling-an-async-redux-action-creator-on-form-submission

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!