Giter Site home page Giter Site logo

redux-form-submit-saga's Introduction

redux-form-submit-saga

Handles redux-form submissions using redux-saga

Install

npm install -S redux-form-submit-saga

Usage

Integrate with Sagas

You can integrate this package with your other sagas as follows:

import {createSagaMiddleware} from 'redux-saga';
import {addFormSubmitSagaTo} from 'redux-form-submit-saga';
import {allMySagas} from '...';

const sagaMiddleware = createSagaMiddleware();
// ... create store with middleware ...
const rootSaga = addFormSubmitSagaTo(allMySagas);
sagaMiddleware.run(rootSaga);

If you need to access the saga directly, it can be imported as formSubmitSaga.

Integrate with Forms

For each form where you want to submit with something async (often), you can setup the submit function like this:

import {reduxForm, Field} from 'redux-form';
import {onSubmitActions} from 'redux-form-submit-saga';

const MyForm = ({handleSubmit}) => (
  <form onSubmit={handleSubmit}>
    <Field component="input" type="text"/>
    <button type="submit">Submit</button> 
  </form>
);

export default reduxForm({
  form: 'myForm',
  onSubmit: onSubmitActions('MY_FORM')
})(MyForm);

This is assuming you are using handleSubmit within your form and not invoking it with an inline handler function.

There are multiple ways to configure onSubmitActions, the simplest being the one above.

onSubmitActions(root: string, transform?: Function)

You pass in a string, and the action types are derived from that with the suffixes: _SUBMIT, _SUCCESS, and _FAILURE. You can optionally provide a transform function which will be used to transform the form values before being added to the submit action.

onSubmitActions(submit: string | Function, success: string, failure: string)

Here you can pass each action type separately. The submit action (first parameter) can be an action creator function if desired.

Handle Submissions using Sagas

Once set up you should be able to do the following:

import * as api from '...';
import {call, put} from 'redux-saga/effects';
import {takeLatest} from 'redux-saga';

function* myFormSaga (action) {
  try {
    const response = yield call(api.submitMyForm, action.payload);
    yield put({type: 'MY_FORM_SUCCESS', payload: response.body});
  } catch (err) {
    yield put({type: 'MY_FORM_FAILURE', payload: {_error: err.message}});
  }
}

export function* watchMyForm () {
  yield* takeLatest('MY_FORM_SUBMIT', myFormSaga);
}

Immutable.js support

If you are using Immutable.js with redux-form, you can import the above functions from redux-form-submit-saga/immutable.

If you want to use ES modules for tree-shaking or other purposes, you'll need to use redux-form-submit-saga/es/immutable directly.

redux-form-submit-saga's People

Contributors

aaronjensen avatar andredp avatar colinbate avatar floriangosse avatar hugobessa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

redux-form-submit-saga's Issues

How to use onSubmitActions in a submit function without using onSubmitKey

I'm trying to create a button-less form.
The problem is that I can't figure out how to use the onSubmitActions function provided by this library directly in the form.
Cause I need to use event.preventDefault so that my form could be submitted.

const EditInput = ({ id, handleSubmit, toggleEditAction, editTodoAction }) => {
  const submit = () => {
    event.preventDefault();
    onSubmitActions('EDIT_TODO_FORM');
    toggleEditAction(id);
  };
  return (
    <form onSubmit={handleSubmit(submit)} onBlur={() => { toggleEditAction(id); }} >
      <Field
        name="text"
        label="What do you wanna ext man"
        type="text"
        component={renderInput}
      />
    </form>);
};

this code does not launch the FORM_SUBMIT and i don't know why

Saga not fired

Hi. I have a similar problem to issue #4 . Seems none of the actions are fired even though I used the addFormSubmitSagaTo function. I also tried also adding the saga to my sagas root.

I think I followed all the steps. Here's my code:

// sagas.ts
import { demoGamesOperations } from './demo-games';
import { all } from 'redux-saga/effects';

export default function* rootSaga() {
  yield all([
    demoGamesOperations(),
  ]);
}
// reducers.ts
import demoGames from './demo-games';
import { reducer as form } from 'redux-form/immutable';

export default {
  demoGames,
  form,
};
// store.ts
import { createStore, applyMiddleware } from 'redux';
import * as withRedux from 'next-redux-wrapper';
import nextReduxSaga from 'next-redux-saga';
import createSagaMiddleware from 'redux-saga';
import { combineReducers } from 'redux-immutable';
import { fromJS } from 'immutable';
import { addFormSubmitSagaTo } from 'redux-form-submit-saga/immutable';

import reducers from 'ducks/reducers';
import allSagas from 'ducks/sagas';

const sagaMiddleWare = createSagaMiddleware();
const rootReducer = combineReducers(reducers);

const middleware = [ sagaMiddleWare ];

export function configureStore(initalState = {}) {

  const store = createStore(rootReducer, fromJS(initalState), applyMiddleware(...middleware));

  const rootSaga = addFormSubmitSagaTo(allSagas);
  store.sagaTask = sagaMiddleWare.run(rootSaga);
  return store;
}

export function withReduxSaga(BaseComponent: any) {

  return withRedux(configureStore)(nextReduxSaga(BaseComponent));
}
// signupform.ts
import * as React from 'react';
import {
  reduxForm,
  Field,
  // WrappedFieldProps,
  // FormProps,
  // InjectedFormProps,
  // SubmitHandler,
} from 'redux-form/immutable';
import styled from 'styled-components';
import Textfield from 'components/form/textfield';
import { connect } from 'react-redux';
import SignupButton from './signup-submit-button';
import validate from './validate';
import { onSubmitActions } from 'redux-form-submit-saga/immutable';

// interface RenderTextFieldProps extends WrappedFieldProps {
interface RenderTextFieldProps {
  placeholder?: string;
  type?: string;
}

const FormError = styled.p`
  top: -25px;
  position: relative;
  color: ${(props) => props.theme.colors.negative};
  margin-bottom: 0;
`;

const renderTextField = ({ input, placeholder, type, meta: { touched, error } }: any) => {

  return (
    <div>
      <Textfield {...input} placeholder={placeholder} type={type} invalid={touched && error} />
      {touched &&
        ((error &&
          <FormError>
            {error}
          </FormError>))}
    </div>
  );
};

class SignupForm extends React.Component<any> {

  public render() {

    const { handleSubmit, invalid } = this.props;
    return (
      <form onSubmit={handleSubmit}>
        <Field
          name="first_name"
          component={renderTextField}
          type="text"
          placeholder="First Name"
        />
        <Field
          name="email"
          component={renderTextField}
          type="text"
          placeholder="Email Address"
        />
        <Field
          name="password"
          component={renderTextField}
          type="password"
          placeholder="Password"
        />
        <Field
          name="password_confirmation"
          component={renderTextField}
          type="password"
          placeholder="Password Confirmation"
        />
        <button type="submit">Sign up</button>
      </form>
    );
  }
}

export default reduxForm({
  form: 'signup',
  validate,
  onSubmit: onSubmitActions('SIGNUP'),
})(SignupForm);
// operations.ts
import { signupUser } from 'services/api';
import { call, put } from 'redux-saga/effects';
import { takeLatest } from 'redux-saga';

function* signupSaga (action: any): any {
  try {
    const response = yield call(signupUser, action.payload);
    yield put({ type: 'SIGNUP_SUCCESS', payload: response });
  } catch (err) {
    yield put({ type: 'SIGNUP_FAILURE', payload: { _error: err.message } });
  }
}

export function* watchSignup() {
  yield takeLatest('SIGNUP_SUBMIT', signupSaga);
}
// api.ts
import * as unfetch from 'isomorphic-unfetch';
import { siteUrl } from 'config';
import { SignupFormValues } from 'pages/auth/signup/components/signup-form/types';
import { toJS } from 'immutable-to-js';

async function callApi(
  method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'DELETE',
  endpoint: string,
  body?: any,
) {

  const fullUrl = `${siteUrl}/api/${endpoint}`;

  const res = await unfetch(fullUrl, {
    method,
    body: body ? JSON.stringify(body) : null,
  });
  if (res.ok)
    return await res.json();
  else
    throw new Error(`Calling API with ${endpoint} endpoint`);
}

export const fetchDemoGames = (isMobile: boolean) => callApi('GET', `games/${isMobile ? 'mobile' : 'desktop'}`);
export const signupUser = (values: any) => callApi('POST', `users`, { user: toJS(values) });

error doesn't work when using with immutable.js

Hi,

First of all awesome library! Very convenient to use by not needing to write our own saga for redux-form.

One thing though, since I'm using immutable.js, SubmissionError doesn't show up in redux-form action because the library is not using the one exported from redux-form/immutable but from redux-form. You may refer to this issue redux-form/redux-form#1713

How to make this library support immutable.js? Thanks.

Best,
Joseph

Timing issue

Hi,
First of all, I've tried your module and the redux-form-saga module and yours works a lot better!

I've noticed that when my saga handles the SUBMIT request too fast and returns a SUCCESS, the SUCCESS action is dispatched before the "redux-form/START_SUBMIT" action and the submit never finishes.
You can replicate this by having a saga directly dispatch the SUCCESS action.
I've solved this by first waiting for the "redux-form/START_SUBMIT" action in my saga before continuing.

export function* saveUserDataSaga(action) {
    // I've added the line below to solve my timing issue
    yield take('redux-form/START_SUBMIT')
    yield put({
        type: SAVE_USER_DATA_SUCCESS,
        payload: action.payload
    })
}

Is this a bug that could be fixed in your module or did I miss something?

Thanks!

why do you compose this saga with root?

Looking at the src code, I see that you compose formSubmitSaga with the user's rootSaga.

Why not have this be a module that you can just import rather than wrapping the root saga?

Was there an implementation difficulty associated with having this form-submit saga be standalone? Or did you craft it this way for usability?

'SUBMIT' suffix never fired?

I'm not getting a 'MYFORM_SUBMIT' action fired when I use your module, and looking at the code I can't see where that would ever get fired as you seem to override it with the transform function immediately after generating it here

All I see in my Redux dev tools is the generic 'FORM_SUBMIT' action, but that's not all that useful to me without doing extra checking in all my sagas. Have I missed something?

Example how to submit remotelly

My form has no submit button inside. I need usable action outside of form. Could you give an example of remote submitting form?

How should I fire redux-form STOP_SUBMIT action ?

Hi,

I trying this lib and it is working just fine, except for this issue.

After my saga runs, STOP_SUBMIT is not dispatched by the form.

This is my saga:

function* authSaga(action) {
  yield put(auth.request());
  const { data, error } = yield call(token, action.payload);
  if (data) {
    yield put(auth.success(data));
  } else {
    yield put(auth.failure(error));
  }
}

export function* watchAuth() {
  yield* takeLatest(actions.SIGNIN_SUBMIT, authSaga);
}

and this is my form:

import React, { Component, PropTypes } from 'react';
import { Field, reduxForm } from 'redux-form';
import { onSubmitActions } from 'redux-form-submit-saga';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import FormControl from 'react-bootstrap/lib/FormControl';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
import Button from 'react-bootstrap/lib/Button';

import styles from '../Signin.less'; // eslint-disable-line

class SigninForm extends Component {

  getValidationState = ({ touched, error, warning }) => {
    if (touched && error) {
      return { validationState: 'error' };
    } else if (touched && warning) {
      return { validationState: 'warning' };
    }
    return undefined;
  }

  renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
    <FormGroup
      className={styles['loginbox-textbox']}
      {...this.getValidationState({ touched, error, warning })}
    >
      <FormControl
        componentClass="input" type={type} placeholder={label}
        className={styles['form-control']}
        {...input}
      />
      {touched && ((error && <HelpBlock>{error}</HelpBlock>) || (warning && <HelpBlock>{warning}</HelpBlock>))}
    </FormGroup>
  )

  render() {
    const { handleSubmit, submitting, error, touched } = this.props;

    return (
      <form onSubmit={handleSubmit}>
        <Field name="username" type="text" label="Email" component={this.renderField} />
        <Field name="password" type="password" label="Password" component={this.renderField} />
        {touched && error && <span>{error}</span>}
        <div className={styles['loginbox-forgot']}>
          <a href>
            Forgot Password?
          </a>
        </div>
        <div className={styles['loginbox-submit']}>
          <Button type="submit" disabled={submitting} bsStyle="primary" block>
            Sign in
          </Button>
        </div>
      </form>
    );
  }

}

SigninForm.propTypes = {
  submitting: PropTypes.bool.isRequired,
  handleSubmit: PropTypes.func.isRequired,
  error: PropTypes.string,
  touched: PropTypes.bool
};

const validate = values => {
  const errors = {};
  if (!values.username) {
    errors.username = 'Required';
  }
  if (!values.password) {
    errors.password = 'Required';
  }
  return errors;
};

// eslint-disable-next-line
SigninForm = reduxForm({
  form: 'signinForm',
  onSubmit: onSubmitActions('SIGNIN'),
  validate
})(SigninForm);

export default SigninForm;

Am I using it wrong?

Thanks

Consider putting an example of form to avoid stupid people like me opening issues

Hello,

I know is kind of weird that I open an issue to prevent people like me opening issues of this kind... but life is sometimes this strange.

My problem was about the onSubmit handler. I was making sure to put the correct onSubmit function on the reduxForm factory:

export default reduxForm({
    form: formConfig.formName,  // a unique identifier for this form
    onSubmit: onSubmitActions(LOGIN),
    initialValues: fromJS({username:'', password:''})
})(LoginForm)

But I was calling the handleSubmit on my form instead of just passing in the handle, so I was doing
<Form horizontal onSubmit={handleSubmit()}> instead of <Form horizontal onSubmit={handleSubmit}>. Probably a stupid error that is totally my fault, but I think it is good to make it noticeable.

Probably what confused me was the following sentence:

This is assuming you are using handleSubmit within your form and not passing it anything.

I supposed that you should call handleSubmit without parameters, but you don't have to call it at all.

Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.