Search code examples
node.jsreactjsreduxgraphqlredux-form

redux-form handleSubmit not sending form data


handleSubmit() isn't sending form data. It appears the configuration object for the fields are undefined for some reason, even though i believe i wired up redux-form correctly.

LoginComponent.js

import { reduxForm } from 'redux-form';

import '../others/styles.css';

const FIELDS = {
  username: {
    type: 'input',
    label: 'Enter username'
  },
  password: {
    type: 'input',
    label: 'Enter password'
  }
};

const Login = (props) => {
  console.log('--------- props: ', props);

  const { fields: { username, password }, handleSubmit, setUsernameAndPassword } = props;

  console.log('-------- username: ', username); // PROBLEM: Returns undefined when it should return the config object for this field
  return (
    <div>
      <Form onSubmit={ handleSubmit(setUsernameAndPassword.bind(this)) } id='login'>
        <Form.Field>
          <label>Username</label>
          <input {...username}
            name='username' />
        </Form.Field>

....

Login.propTypes = {
  handleSubmit: React.PropTypes.func,
  fields: React.PropTypes.array,
  setUsernameAndPassword: React.PropTypes.func
};

export default reduxForm({
    form: 'LoginForm',
    fields: Object.keys(FIELDS)
})(Login);

LoginContainer.js

import { connect } from 'react-redux';
import { graphql } from 'react-apollo';

import Login from '../components/LoginComponent';
import LoginMutation from '../graphql/LoginMutation.gql';
import { types as typesAuth } from '../reducers/auth';

const gqlLogin = graphql( LoginMutation, {
  props: ({mutate}) => ({
    login: async function loginWithUsernameOrEmail(variables) {
      try {
        const result = await mutate({variables});
      } catch (err) {
        console.log('GQL Error: ', err);
      }
    }
  })
})(Login);

export default connect(
  state => ({
    isLoggedIn: state.auth.isLoggedIn
  }),
  dispatch => ({
    setUsernameAndPassword: (data) => { // PROBLEM: Why is data empty??
      console.log('--------- data: ', data);
      dispatch({
        type: typesAuth.SET_USERNAME_PASSWORD,
        payload: {
          username: data.username,
          password: data.password
        }
      });
    }
  }),
)(gqlLogin);

reducers/index.js

import { reducer as auth } from './auth';
import { reducer as formReducer } from 'redux-form';

export default {
  auth,
  form: formReducer
};

reducers.js

// Modules
import appReducers from '../modules/root/reducers/';
import authReducers from '../modules/auth/reducers/';

module.exports = {
  ...appReducers,
  ...authReducers
};

redux.js

// Imports
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';

// Reducers
import Client from './client';
import reducers from './reducers';

const devtools = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

module.exports = createStore(
  combineReducers({
    ...reducers,
    apollo: Client.reducer()
  }),
  compose(
    applyMiddleware(Client.middleware()), devtools()
  ),
);

auth.js

// Constants
export const types = Object.freeze({
  SET_USERNAME_PASSWORD: 'AUTH/SET_USERNAME_PASSWORD'
});

// Default State
const DEF_STATE = {
  isLoggedIn: false,
  username: null,
  password: null
};

export const reducer = (state = DEF_STATE, action) => {
  let newState;
  switch (action.type) {
    ...
    case types.SET_USERNAME_PASSWORD:
      newState = {
          ...state,
          username: action.payload.username,
          password: action.payload.password
      };
      break;
    default:
      newState = state;
  }
  return newState;
};

Solution

  • You need to use Field components from redux-form to tie the individual inputs to the redux store (see docs).

    The "Simple Form" Example in the redux-form docs is a good demonstration of how to do this, simply import the Field component from redux-form and use it to describe your inputs. In your case it would be something like this:

    import { reduxForm, Field } from 'redux-form';
    
    const Login = (props) => {
      console.log('--------- props: ', props);
    
      const { handleSubmit, isLoggingIn, setUsernameAndPassword } = props;
    
      return (
        <div>
          <Form onSubmit={ handleSubmit(setUsernameAndPassword.bind(this)) } id='login'>
            <Form.Field>
              <label>{i18n.t('auth.username')}</label>
              <Field
                component="input"
                name="username"
                placeholder={i18n.t('utils.and',{item1: i18n.t('auth.username'), item2: i18n.t('auth.email')})}
              />
            </Form.Field>
    
    ....
    

    Hope this helps!