Search code examples
reactjsreact-nativereduxredux-form

Passing values to action creator using Redux and React Native


How can I send the values from the reduxForm fields to my login actionCreator so that I can generate a dispatch for authentication from there. Here is what I have so far. Basically on submit, I want the login action creator to be called with the values from the "form"

import React, {Component} from 'react';
import {TouchableHighlight,Alert, AsyncStorage,StyleSheet,Text, TextInput, TouchableOpacity, View} from 'react-native';
import {Actions} from 'react-native-router-flux';
import { Field,reduxForm } from 'redux-form'
import { connect } from 'react-redux'

import { login } from '../../actions/user.js'


// const submit = values => {
//    authenticate()
//    //login(values.email, values.password);
// }

const renderInput = ({ input: { onChange, ...restInput }}) => {
  return <TextInput style={styles.input} onChangeText={onChange} {...restInput} />
}

const Authentication = (props) => {
 const { handleSubmit } = props
 const {login} = props

 const {
    container,
    text,
    button,
    buttonText,
    mainContent
  } = styles
  
    return (
       <View style={styles.container}>
          
         <Text>Email:</Text>
         <Field name="email" component={renderInput} />
         
         <Text>Password:</Text>
         <Field  name="password" component={renderInput} />

      <TouchableOpacity onPress={handleSubmit(login)}>
        <Text style={styles.button}>Submit</Text>
      </TouchableOpacity>


      </View>
    );
  
}


function mapStateToProps (state) {
  return {
    userData: state.userData
  }
}

function mapDispatchToProps (dispatch) {
  return {
    login: () => dispatch(login())
  }
}



Authentication = reduxForm({
  form: 'loginForm'  // a unique identifier for this form
})(Authentication)

// You have to connect() to any reducers that you wish to connect to yourself
const AuthenticationComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(Authentication)

export default AuthenticationComponent


Solution

  • From the redux-form documentation I found that onSubmit passes a value to the function passed to it. In the case of this form, the value passed is a JSON object. The solution to pass values to my action creator was the following.

    Expose the function with an variable as an input in the mapDispatchToProps function:

    function mapDispatchToProps (dispatch) {
      return {
        login: (val) => dispatch(login(val))
      }
    }

    Then in the component:

    <TouchableOpacity onPress={handleSubmit(login)}>
            <Text style={styles.button}>Submit</Text>
          </TouchableOpacity>

    Hope this helps.