Giter VIP home page Giter VIP logo

redux-form's Introduction

redux-form


You build great forms, but do you know HOW users use your forms? Find out with Form Nerd! Professional analytics from the creator of Redux Form.


NPM Version NPM Downloads Build Status codecov.io Code Climate styled with prettier Twitter URL Patreon Backers on Open Collective Sponsors on Open Collective

redux-form works with React Redux to enable an html form in React to use Redux to store all of its state.


๐Ÿ’ฐPsst!! Do you know React and Redux? Sign up with Triplebyte to get offers from top tech companies! ๐Ÿ’ฐ


โš ๏ธ ATTENTION โš ๏ธ

If you're just getting started with your application and are looking for a form solution, the general consensus of the community is that you should not put your form state in Redux. The author of Redux Form took all of the lessons he learned about form use cases from maintaining Redux Form and built ๐Ÿ React Final Form, which he recommends you use if you are just starting your project. It's also pretty easy to migrate to from Redux Form, because the <Field> component APIs are so similar. Here is a blog post where he explains his reasoning, or there are two talks if you prefer video. Formik is also a nice solution.

The only good reason, in the author's view, to use Redux Form in your application is if you need really tight coupling of your form data with Redux, specifically if you need to subscribe to it and modify it from parts of your application far from your form component, e.g. on another route. If you don't have that requirement, use ๐Ÿ React Final Form.

Installation

npm install --save redux-form

Documentation

๐Ÿ– Code Sandboxes ๐Ÿ–

You can play around with redux-form in these sandbox versions of the Examples.

Videos

A Practical Guide to Redux Form โ€“ React Alicante 2017
A Practical Guide to Redux Form โ€“ React Alicante 2017
Abstracting Form State with Redux Form โ€“ JS Channel 2016
Abstracting Form State with Redux Form โ€“ JS Channel 2016

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! ๐Ÿ™ [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

redux-form's People

Contributors

asazernik avatar bbb avatar bbenezech avatar bmv437 avatar clayne11 avatar dagstuan avatar danielrob avatar dependabot[bot] avatar erikras avatar esetnik avatar gabrielecirulli avatar gitname avatar greenkeeperio-bot avatar gustavohenke avatar huan086 avatar iamandrewluca avatar jedwards1211 avatar joshgagnon avatar kevinzwhuang avatar mihirsoni avatar mikekidder avatar ncphillips avatar ooflorent avatar puradox avatar renatoagds avatar skovhus avatar timhwang21 avatar vladshcherbin avatar vtaits avatar yesmeck 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  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  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  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

redux-form's Issues

Allow to dispatch an action on async form validation

redux-form doesn't seem to allow to dispatch an action on async validation for now.
However, I seperated ajax logic with async action and middleware like this:

const fetch = createAction('SEARCH_FETCH', 
  (query) => api('GET', '/api/search', {query}));

// This returns a Promise for searching 'Hello, world!'
// and this also dispatches 'SEARCH_FETCH' when fetching is complete.
store.dispatch(fetch('Hello, world!'));
.then(result => {
  console.log(result);
});

If redux-form allows to dispatch an (async) action on form validation, I think it can seperate API call logic and validation logic.

const checkUsername = createAction('SIGNUP_CHECK_USERNAME', 
  (username) => api('GET', '/api/signup/checkUsername', {username}));
function validateFormAsync(data, dispatch) {
  // In this case, checkUsername action is ignored by reducers
  return dispatch(checkUsername(data.username));
  .then(action => {
    if (action.error) {
      return {
        username: 'Internal server error'
      };
    }
    return {
     username: action.payload
    };
  });
}

Here's the source code of 'api' function: https://gist.github.com/yoo2001818/05aad13f1af7fb5eaf38

Allow null validation

Having to create dummy functions that return an empty object adds unnecessary code, please allow for null validator

Can slice name depend on props?

Apologies if I missed this. Can the slice name depend on props? This could be useful for forms "bound" to specific IDs. For example imagine an address book where every item is editable at the same time. Its key could be a function: props =>contacts/${props.id}`. Makes any sense?

Rename action types

Minor thing, but I suggest redux-form/CHANGE_FIELD, etc, as action types. We wanted to suggest this convention to third party packages so their action names don't clash.

Display errors after onSubmit

How do you display errors received from the server after the form has been submitted? For example, the user saves a form and the server responds with errors on specific fields.

I understand how validate() and asyncValidate() work but these validators are fired before submitting the form. Thanks!

Deep form structure and deep validation

Hi! Thank you for your library.

I want to use redux-form with complex deep structures. Simple example of complex structure I want to use:

{
  users: Array[
    {
      name: string,
      group: {
        name: string
      }
    }
  ],
  confirmed: boolean
}

What are you think, is it possible to implement in redux-form?

Also I have validator for complex deep structures.
I'm in deep refactoring right now, but I'll release a new version soon with async validation, simpler API, etc.
So, could you change API of validator from ({}) => {} to something like that:

type ValidatorResult = {valid: true, [key: string]: any}
type Validator = (data: Object) => ValidatorResult | Promise<ValidatorResult>

And check only for valid property, not for every object key.
With that API I could use my validation library with your form library.

Dynamic Form input can't get focus

First off, loving this library, thanks for the hard work you've clearly put in.

I'm having some issues with the DynamicForm in the README. Most of this code is stripped down versions from the examples.

I have a <BaseForm> that loops over and renders all inputs.

Firstly I create <DefinedForm /> with connectReduxForm with hard coded fields.
Secondly I create <DynamicForm /> that takes the list of fields and calls connectReduxForm to create a new <Component /> with dynamic fields.

Finally I render both forms into one <ContainerComponent />.

I can happily fill in the <DefinedForm />. I can type in the input and see all interacts appear in <DevTools />.

However when I click on the <DynamicForm /> I cannot type anything. In the <DevTools /> I get a redux-form/FOCUS event but nothing more. Focus is not actually given to the input (I added style to focused inputs).

Am I doing something wrong or missing something out here?

import { connectReduxForm } from 'redux-form';
import React, { Component, PropTypes } from 'react';


class BaseForm extends Component {
  render() {
    const { fields } = this.props;
    return (
      <div formKey={this.props.formKey} >
        {Object.keys(fields).map(fieldName => <div key={fieldName}>
          <label>{fieldName}</label>
          <input type="text" {...fields[fieldName]}/>
        </div>)}
      </div>
    );
  }
}

var DefinedForm = connectReduxForm({
  form: 'contact',
  fields: ['name'],
  validate: (data) => { return {}; }
})(BaseForm);

class DynamicForm extends Component {
  render() {
    const { formName, fieldsNeeded } = this.props;
    var DynamicInnerForm = connectReduxForm({
      form: formName,
      fields: fieldsNeeded,
      validate: (data) => { return {}; }
    })(BaseForm);

    return <DynamicInnerForm formKey={this.props.formKey} />;
  }
}

class NestedDefinedForm extends Component {
  render() {
    return <DefinedForm />
  }
}

class ContainerComponent extends Component {
  render() {
    return (
      <div>
        <h1>DefinedForm</h1>
        <DefinedForm
          formKey={'DefinedForm'} />

        <h1>NestedDefinedForm</h1>
        <NestedDefinedForm
          formKey={'NestedDefinedForm'} />

        <h1>DynamicForm</h1>
        <DynamicForm
          formKey={'DynamicForm'}
          formName={'contact'}
          fieldsNeeded={['name']} />
      </div>
    );
  }
}


export default ContainerComponent;

How to dynamically add input fields

Say I have a job application form and there are fields for your previous working experience.

Since you have multiple jobs before, I need a way to dynamically add those field.

Any suggestion for this case? Thanks.

Handling custom form elements

I'm curious how one would go about using this library against a custom form element (whatever that element may be). Specifically how does one plugin to the onBlur and onChange events which expect synthetic events. I'm not sure if it's possible to generate custom react synthetic events (my searching proved fruitless although I'm not yet an expert in all this). Perhaps an override could be added for custom elements that accepts a more minimal api?

fails on Safari

Testcase in CoffeeScript, using React 0.14 beta to be sure but also not working on 0.13:

React = require 'react'
ReactDOM = require 'react-dom'
redux = require 'redux'
reduxDom = require 'react-redux'

E = React.createElement
N = {}

reducer = (-> {})
store = redux.createStore reducer

reduxForm = require 'redux-form'

class Failer extends React.Component
  render: ->
    return E 'h1', N, "No problem in this browser"

Fail = reduxForm.connectReduxForm(
  form: 'test'
  fields: ['foo']
) Failer

class Application extends React.Component
  render: ->
    E reduxDom.Provider, store: store,
      E Fail, N

ReactDOM.render (E Application), document.body

In Safari (not Chrome or FireFox), this results in a mysterious

[Error] TypeError: Requested keys of a value that is not an object.
    (anonymous function) (undefined, line 13)
    eval code
    eval ([native code], line 0)
    (anonymous function) (bundle.js, line 1978)
    __webpack_require__ (bundle.js, line 521)
    fn (bundle.js, line 76)
    eval code
    eval ([native code], line 0)
    (anonymous function) (bundle.js, line 554)
    __webpack_require__ (bundle.js, line 521)
    (anonymous function) (bundle.js, line 544)
    global code (bundle.js, line 545)

(hot-dev-server)

[Error] TypeError: Requested keys of a value that is not an object.
    (anonymous function) (bundle.js, line 17)

(minified production build)

If you render Failer instead of Fail, it works.

Plain JavaScript version:

var Application, E, Fail, Failer, N, React, ReactDOM, reducer, redux, reduxDom, reduxForm, store,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

React = require('react');

ReactDOM = require('react-dom');

redux = require('redux');

reduxDom = require('react-redux');

E = React.createElement;

N = {};

reducer = (function() {
  return {};
});

store = redux.createStore(reducer);

reduxForm = require('redux-form');

Failer = (function(superClass) {
  extend(Failer, superClass);

  function Failer() {
    return Failer.__super__.constructor.apply(this, arguments);
  }

  Failer.prototype.render = function() {
    return E('h1', N, "No problem in this browser");
  };

  return Failer;

})(React.Component);

Fail = reduxForm.connectReduxForm({
  form: 'test',
  fields: ['foo']
})(Failer);

Application = (function(superClass) {
  extend(Application, superClass);

  function Application() {
    return Application.__super__.constructor.apply(this, arguments);
  }

  Application.prototype.render = function() {
    return E(reduxDom.Provider, {
      store: store
    }, E(Fail, N));
  };

  return Application;

})(React.Component);

ReactDOM.render(E(Application), document.body);

I'd have made an online test case but react-redux is not on a cdn.

De-emphasize ES7 in docs

The important part is that it's reducer factory + HOC.
ES7 decorator is just neat syntax sugar for applying HOC, rather than a central idea of this repo.
Currently, README makes it sound like using it requires enabling ES7 decorators, which is not the case.

I suggest downgrading the examples to ES6 like in React Redux new README, and maybe showing ES7 decorator syntax as bonus at the end.

Reusable Custom Form Components

In an application that contains many forms, it is advantageous to create reuseable form components.

For example, consider a Numbercomponent. It's propTypes may look like:

{
  name: PropTypes.string.isRequired,
  required: PropTypes.bool,
  label: PropTypes.string,
  value: PropTypes.number
}

This Number component would contain it's own validation which ensures the value is a number.

How can I create this Number component and force redux-form to depend on the component's validation? I am trying to design this in a way where I can just use the Number component in any form and get the automatic validation.

The only idea I have at the moment is that the validate function could look through this.refs and check if the component has a method called isValid and verify if it returns true.

Thoughts?

Support Redux 2.0

Can't use redux-form with latest redux and redux dev tools atm. Thanks!

Export actions on top level

I think it would be useful, if we exported all actions on the top level object.

The use cases for this are for example:

  • triggering a change to a form outside of a component (for example when we need to prefil it with data we do not have at reducer-init time)
  • resetting a form (as mentioned in #11)

In code:

import { change, reset } from 'redux-form';

// change a form field or initially populate it prior to rendering
change('myForm', 'myField', 'whoop');

// reset a form
reset('myForm');

Thoughts?

Global form errors

redux-form does not seem to support global form errors (as opposed to field errors). For example, if the server responds with a 500 error, it is essential that the user be informed of this problem. But this error doesn't really apply to a field, per se.

I am currently hacking this functionality together via the formReducer.plugin() API, which is injecting a custom errors property into every form's state. I am then dispatching a custom FORM_ERRORS event with form (name) and errors (array of error strings) attached. My plugin listens for this action and merges in the errors.

Is there a better way to accomplish this using redux-form built-ins? If not, I propose that global form errors be adopted as a feature. My first thought is that a redux-form/FORM_ERRORS action could be exposed, which could be dispatched when the server response is received.

Submit form on change

Hi, thanks for awesome lib {it really made my life simpler}.
Is it possible to submit form with changed data when my component triggers onChange event?
Basically i want to update item in state when user selected type of this item in form.

Sorry for stupid question might be it is in docs, but i don't see it -_-

Custom bindActionCreators

Do you think it is a good idea to introduce a custom binding function?

I feel that it's not a lot of work to just write

function mapDispatchToProps(dispatch) {
  return {
    ...bindActionCreators(actionCreators, dispatch),
    dispatch
  }
}

in order to receive dispatch. If not anything else, it would be more obvious what's happening. Just some food for thought, I'm just curious about your opinion.

Form's state is null by default

I'm trying to jump from 0.1.3 to 0.2.4 and found a pitfall which I couldn't get rid of.

The form is rendered within bootstrap popup.

form

I'm using reselect for lazy evaluations and in this particular case to define whether user can add widget or not.

import { createSelector } from 'reselect';
const widgetNameSelector = state => state.addWidgetForm.data.name;
const widgetTypeSelector = state => state.addWidgetForm.data.type;
const canAddSelector = createSelector(
  [widgetNameSelector, widgetTypeSelector],
  (name, type) => !!name && !!type  // both fields should not be empty
);

@connect(
  (state) => {
    return {
      form: state.addWidgetForm
      canAdd: canAddSelector(state)
    };
  }
)
class AddWidgetForm extends Component { ... }

addWidgetForm wasn't equal null at start in [email protected], so I could rely on the structure in reselect state.addWidgetForm.data.name.

In [email protected] it equals null.
devtools

Of course I have error in this function:

const widgetNameSelector = state => state.addWidgetForm.data.name;

Any suggestions? Is it correct behaviour?

Using initializeWithKey with ES7 Decorators

Is it possible to use initializeWithKey alongside the ES7 decorator?

It looks like it's possible to do, but my react-fu isn't sufficient to understand how to achieve it.

Multiple forms on page

Imagine you have multiple items on page and all of them are editable. So every item has its own form. Then textual ID in reduxForm('itemEditForm') is not enough.

Is there a solution for this situation?

Server Side async validation

I have async and sync validators. Then form is rendering sync validator triggers by default and can validate initial state of form, but how to trigger async validator?

I have tried trigger next code at the transition hook, but did not have success in that. Thank you.

dispatch(startAsyncValidation('formName'))

Is it possible to access original props after applying decorator?

I'm wondering if I'm doing something wrong with this decorator; when I apply it to a component I can no longer access things like actions passed via props.

In the beginning of the render method, I logged this.prop and can see the actions that I passed, but as soon as I add the decorator the only props available are the ones from redux-form. Am I making a mistake here?

How to reset the form after async call

Say I have a login form that submits credentials to my api server. I don't want to call this.reset() in the components submit handler because I'm not sure yet whether the user logged in successfully.

So my form component listens on something like auth.isLoggedIn from global state and in componentWillReceiveProps I check the value of this prop. If nextProps.isLoggedIn is true, I redirect and now I want to reset the form. The trouble is, resetting the form within componentWillReceiveProps leads to an infinite loop. So the question I have is where is the best place to call reset without getting into this issue?!

Thanks!

Validation state in store

Hello!

Please, can you help me? I want to store the form validation state in the form reducer. How I can do this?

synchronous validation on blur or submit?

Is there an option we can set that tells our form component to fire the synchronous validation function only onBlur or onSubmit for the entire form? Currently the validate function is fired for both onChange and onBlur.

A problem I am facing is when the server returns errors after the form has been submitted. If my form errors are only shown when field.error && field.touched, the user will not see errors set after submission because the fields are not touched yet.

If instead we use field.error && field.pristine we get the opposite effect - the user can see submission errors for fields but once we touch the fields all the errors become hidden.

Ideally there would be another prop called submitted or something along those lines that would tell us if the form has been submitted at least once already.

Cannot read property 'initial' of undefined

Getting this error since updating from 0.5 to 0.7

{"error":"TypeError: Cannot read property 'initial' of undefined\n    at ReduxForm.render (/[REDACTED]/node_modules/redux-form/lib/reduxForm.js:67:45)\n    at [object Object].ReactCompositeComponentMixin._renderValidatedComponentWithoutOwnerOrContext (/[REDACTED]/node_modules/react/lib/ReactCompositeComponent.js:789:34)\n    at [object Object].ReactCompositeComponentMixin._renderValidatedComponent (/[REDACTED]/node_modules/react/lib/ReactCompositeComponent.js:816:14)\n    at [object Object].wrapper [as _renderValidatedComponent] (/[REDACTED]/node_modules/react/lib/ReactPerf.js:70:21)\n    at [object Object].ReactCompositeComponentMixin.mountComponent (/[REDACTED]/node_modules/react/lib/ReactCompositeComponent.js:237:30)\n    at [object Object].wrapper [as mountComponent] (/[REDACTED]/node_modules/react/lib/ReactPerf.js:70:21)\n    at Object.ReactReconciler.mountComponent (/[REDACTED]/node_modules/react/lib/ReactReconciler.js:38:35)\n    at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (/[REDACTED]/node_modules/react/lib/ReactMultiChild.js:192:44)\n    at ReactDOMComponent.Mixin._createContentMarkup (/[REDACTED]/node_modules/react/lib/ReactDOMComponent.js:289:32)\n    at ReactDOMComponent.Mixin.mountComponent (/[REDACTED]/node_modules/react/lib/ReactDOMComponent.js:199:12)โ€}

data not being passed into onSubmit handler

For whatever reason, I am getting a synthetic event and not the form data object.

I can solve the problem by passing the data property into the handler, but I don't see you doing that in these examples, so just a little bit confused.

Any idea what I might be doing wrong?

Make the `handleChange` prop work with checkboxes/radios

Right now handleChange doesn't work out of the box with checkboxes/radio buttons. In my form, I wrote a small wrapper function like this:

// An expression to handle checkboxes.
const handleCheckboxChanged = name => event => handleChange(name, !!event.target.changed)(event);

But it would be nicer and easier to avoid errors if handleChange supported checkboxes by default.

Additionally, handleBlur doesn't check for undefined explicitly, so it doesn't work at all with the changedproperty.

HandleChange vs HandleBlur documentation

Both handleBlur and handleChange have repeated text: A function to call when the form field is blurred. I believe different language should probably go there for handleChange. For example if a checkbox is checked, or a select dropdown is selected this should probably be called. It may be valid for a text input box.. (i.e. blur and onchange happen similarly).

screen shot 2015-09-03 at 2 04 54 pm

Example for file Upload

Hey! awesome work with redux-form!

I'm using it at production, and I'm going to use it for file inputs, but I would appreciate an example or ideia of how it would be done with redux-form.

thanks!

Documentation about propTypes may be wrong

In the readme at line 120 it says:

class ContactForm extends Component {
  static propTypes = {
    fields: PropTypes.object.isRequired,
    handleSubmit: PropTypes.func.isRequired
  }

However, with these deps in package.json:

    "babel": "^5.8.21",
    "babel-core": "^5.8.22",
    "babel-loader": "^5.3.2",
    "webpack": "^1.12.0",
    "webpack-dev-server": "^1.10.1"

I had to change the line to:

  static propTypes: {

Feature Idea: Allow tracking of onFocus

  • Provide a handleFocus prop to be given to an input's onFocus.
  • Keep a focused boolean flag for each field in state.
  • Keep a visited boolean flag for each field that is set to true on first focus and only unset on initialize or reset.
  • Provide a currentFocus prop to the whole form with the currently focused field.

From discussion on slack with @olivierrr.

Use simple container component

What do you think about simply using a component that pass necessary functions to the it's children callback? Example implementation:

<Validate sliceName="foo">
  {(props) => {<Form {...props}>}}
</Validate>

I personally prefer to use components and children callbacks over blackbox decorators on classes. Redux also gives this options with the <Provider> and <Connector> components.

Validation in submission handler

First off, thanks for making this helpful library.

I'm running into a bit of difficulty with how to handle working with backends where validation and creation aren't necessarily separate steps.

Specifically, in the case of many user registration forms the only way to test if a username is taken is to try registering that user. So there is only a single backend API available.

As far as I can tell, there are two potential places for putting this logic:

  1. In an asynchronous validation handler. This works for doing validation, but it doesn't seem to be possible to dispatch actions from there (and also feels slightly wrong). For example, I can't find a clear way of dispatching the server-provided ID into the Redux state when working through the async validator.
  2. The submission handler. This works for submission and dispatching of state, but there doesn't seem to be any way of invalidating a form in case the submission failed.

Thanks for clarifying the best way to do this! (My natural instinct would be to allow the submission handler to return a validation object.)

Remove dependency on Redux and React Redux

I may be wrong, but I'm not convinced that this library needs to depend on Redux or React Redux.
In particular, I'm not convinced that @reduxForm should use connect() inside.

Why not let the user take care of connecting? Then they understand how it binds to Redux, can customize the connection point (#4) by using connect() API, and it's intuitive where the bound state will appear.

It's slightly more typing but I think the benefits outweigh the downsides.

Instead of

import React, {Component, PropTypes} from 'react';
import reduxForm from 'redux-form';

@reduxForm('contacts', contactValidation)
export default class ContactForm extends Component {

you'd write

import React, {Component, PropTypes} from 'react';
import reduxForm from 'redux-form';

@connect(state => ({ form: state.contacts })) // or wherever you mount your reducer
@reduxForm(contactValidation)
export default class ContactForm extends Component {

The component generated by ContactForm would just accept dispatch and form state as props. It wouldn't need to worry which version of React Redux you use (or even if you use alternative bindings), as long as you pass dispatch and form.

This also opens up for reducers that delegates forms by dynamic IDs. E.g. you may have editItemForms reducer that calls ReduxForm-generated reducer for state.editItemForms[itemId]. And you can connect it to a form component, given a userId, thanks to React Redux API letting you use props:

import React, {Component, PropTypes} from 'react';
import reduxForm from 'redux-form';

@connect(
  state => ({
    forms: state.editItemForms
  }),
  null,
  ({ forms }, dispatchProps, parentProps) => ({
    ...parentProps,
    ...dispatchProps,
    form: forms[parentProps.itemId]
})
@reduxForm(contactValidation)
export default class ContactForm extends Component {

Async validation requires a 'valid' attribute?

I was trying to use async validation, but I'm not able to submit the form due to unknown reason.

It turns out that returning an empty object isn't accepted as a valid form.

function validateContactAsync(data, dispatch) {
  // This doesn't validate the form!
  return Promise.resolve({});
}

I looked at the redux-form's code and found that isAsyncValid() function only looks at the 'valid' attribute of returned object, unlike isValid() function.
Which means, this works:

function validateContactAsync(data, dispatch) {
  // This does validate the form.
  return Promise.resolve({valid: true});
}

Is this an expected behavior? I think sync / async form validation acting differently is wrong.

Following semver

Are you willing to follow semver more closely? :) I know redux-form is very very young, but I feel that it might be a good thing now to at least signal breaking changes by bumping the minor version, instead of just the patch version. Thoughts on this?

Can I use redux-form isomorphically?

For example. I have simple SingUp form

import React, {PropTypes, Component} from 'react';
import {connectReduxForm} from 'redux-form';

@connectReduxForm({
  form: 'singup',
  fields: ['name']
})
class SingUp extends Component {
  static propTypes = {
    fields: PropTypes.object
  };

  render() {
    const {fields: {name}} = this.props;

    return (
      <form action="/singup" method="POST">
        <input {...name} type="text"/>
        <div className="errors">{name.error || null}</div>
        <button type="submit">Submit</button>
      </form>
    );
  }
}

This component renders on the server.
As I do no have any js handlers for form submit on the client (requirements), then I submit form from the client, post request will passed to the server, server will validate data and send the result.

The questions is, how to pass form validation result to redux-form on the server?

weird validation behavior

asyncvalidation

This is the timeline of events

sync rule: email is required
async rule: email can't be [email protected]

user selects input
user types [email protected]
[form is valid, since async rule has not started yet]
user selects another input
[async validation starts]
[async validation ends]
form is invalid

The problem is my email input is my last input, so instead of user selects another input the user will click submit and this will not trigger the async validation at all. Well, it will after the submit happens.

Can we find a way to solve this scenario?

Feature Idea: connectReduxFormReadonly()

connectReduxFormReadonly() would be a decorator for a component that wanted to subscribe to a form's state โ€“ data, dirty/pristine, and valid/invalid โ€“ without having any state-mutating functions provided.

Based on slack conversation with @olivierrr.

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.