Beginner’s
Tutorial (Part-2):
How to
Integrate
Redux-Saga in
React Native
App
www.bacancytechnology.com
We have learned and implemented the
basics of redux-form in our previous
tutorial: Integrate Redux Form (Part-1). You
can visit the tutorial if you don’t have a
basic idea of Redux Form or are struggling
to use it in your application. Now, it’s time
to step up and introduce redux-saga with
redux form. Are you looking for a simple
tutorial to get started with redux
middleware in your react native
application? If yes, then you have chosen
the correct blog!
In this tutorial, we will implement an
authentication module in our demo
application using redux-saga and redux
form.
Goal: Simple
Redux-Form &
React-Saga
Example
Before moving towards implementing our
authentication module, watch the video
below to have a better idea of the demo
application.
Tutorial
Takeaway
Redux-Saga
Redux-Form
Register
Login
Dashboard
Field Array – Field Array component is
used for rendering an array of fields.
Wizard Form – The common pattern for
separating a single form into different
input pages is Wizard.
Mainly we will learn about-
The demo will contain an Authentication
module in which we have used redux-form.
The module will have-
Use of two redux-form features:
And also called Firebase REST API from the
Login and Register module.
So, we are clear with the requirements and
what the demo will contain. Without
wasting more time, let’s get started with
building our demo application.
Redux Store
Set up
The very first step will be setting up the
store.
For connecting the store to your
application, open app/index.js
app/index.js
import { store } from 'store'
import { Provider as ReduxProvider } from
'react-redux'
export default () => (
<ReduxProvider store={store}>
<App/>
</ReduxProvider>
)
Individual action.js and saga.js file for the
Register and Login Page (which we will see
in the coming sections)
A folder named store having three files –
index.js, reducers.js, and sagas.js
So, now the store is accessible through our
entire application. It’s time to use the store in
our app. For that, we will need to do two things-
store/index. js
import createSagaMiddleware from 'redux-
saga';
import {createStore, applyMiddleware}
from 'redux';
import {combinedReducers} from
'./reducers';
import rootSaga from './sagas';
const sagaMiddleware =
createSagaMiddleware();
const middlewares = [sagaMiddleware];
const store =
createStore(combinedReducers,
applyMiddleware(...middlewares));
sagaMiddleware.run(rootSaga);
export {store};
store/reducers.js
import {combineReducers} from 'redux';
import {reducer as formReducer} from
'redux-form';
export const combinedReducers =
combineReducers({
form: formReducer,
Auth: AuthReducer,
});
store/sagas.js
import {all} from 'redux-saga/effects';
import loginScreenSaga from
'screens/Login/saga';
import signupScreenSaga from
'screens/Register/saga';
function* rootSaga() {
yield all([loginScreenSaga(),
signupScreenSaga()]);
}
export default rootSaga;
Register
RegisterPageOne.js
RegisterPageTwo.js
RegisterPageThree.js
We will separate the Register form into
separate pages of inputs named-
This pattern of splitting is known as Wizard
Form.
Register/index.js
To separate the form into small forms we
will use a state variable- page for keeping
track of the page to be rendered.
import React, { useState } from 'react’
import { ScrollView } from 'react-native'
import RegisterPageOne from
'./RegisterPageOne'
import RegisterPageTwo from
'./RegisterPageTwo'
import RegisterPageThree from
'./RegisterPageThree'
const Register = (props) => {
const [page,setPage] = useState(1)
const onSubmit = (Values) => console.log(Values)
const goToNextPage = () => setPage( page =>
page + 1 )
const goToPrevPage = () => setPage( page =>
page - 1 )
return (
<ScrollView>
{page === 1 && <RegisterPageOne nextPage=
{goToNextPage} />}
{page === 2 && <RegisterPageTwo nextPage=
{goToNextPage} prevPage={goToPrevPage} />}
{page === 3 && <RegisterPageThree onSubmit=
{onSubmit} prevPage={goToPrevPage} />}
</ScrollView>
)
}
export default Register
Register/RegisterPageOne.js
RegisterPageOne is our first component
which will have two fields : Full Name and
User Name.
import React from 'react'
import { View } from 'react-native'
import { Field, reduxForm } from 'redux-
form'
import { FormInput , CustomButton } from
'components'
import { usernameRequired ,
fullnameRequired } from 'utils/Validations'
const RegisterPageOne =
({handleSubmit,nextPage}) => {
return (
<View>
<Field
name="fullName"
component={FormInput}
validate={[fullnameRequired]}
placeholder="Enter Full Name"
/>
<Field
name="userName"
component={FormInput}
validate={[usernameRequired]}
placeholder="Enter User Name"
onSubmitEditing = {handleSubmit(nextPage)}
/>
<CustomButton
buttonLabel="Next"
onPress={handleSubmit(nextPage)}
/>
</View>
)
}
export default reduxForm({
form: 'register-form',
destroyOnUnmount: false,
forceUnregisterOnUnmount: true
})(RegisterPageOne)
Register/RegisterPageTwo.js
RegisterPageTwo is our second component
having three fields: Mobile No, Email, and
Hobbies. The input for hobbies uses the
FieldArray API to render multiple inputs to
the user. We will also add validation to the
input fields.
import React from 'react'
import { StyleSheet, View , Text } from
'react-native'
import { Field, FieldArray, reduxForm } from
'redux-form'
import { DeleteButton, CustomButton,
FormInput } from 'components'
import { emailRequired, mobileNoRequired,
validateEmail, validateMobileno } from
'utils/Validations'
const renderHobbies = ({ fields, meta : {error
, submitFailed } }) => {
return(
<View>
<CustomButton
buttonLabel={“Add Hobby”}
onPress={() => fields.push({})}
/>
{fields.map((hobby,index) => (
<View key={index}>
<Field
name={hobby}
placeholder={`Hobby #${index + 1 }`}
component={FormInput}
/>
<DeleteButton onDelete={() =>
fields.remove(index)} />
</View>
))}
{ submitFailed && error && <Text>{error}
</Text> }
</View>
)
}
const validate = (values,props) => {
const errors = {}
if (!values.hobbies ||
!values.hobbies.length) errors.hobbies = {
_error : “Add at least One hobby” }
else{
const hobbiesArrayErrors = []
values.hobbies.forEach((hobby,index)=>{
if (!hobby || !hobby.length)
hobbiesArrayErrors[index] =
HOBBY_REQUIRED
})
if(hobbiesArrayErrors.length)
errors.hobbies = hobbiesArrayErrors
}
return errors
}
const RegisterPageTwo =
({prevPage,handleSubmit,nextPage}) => {
return (
<View>
<Field
name="mobileNo"
component={FormInput}
placeholder={“Enter Mobile Number”}
validate=
{[mobileNoRequired,validateMobileno]}
/>
<Field
name="email"
component={FormInput}
placeholder={“Enter email”}
validate={[emailRequired,validateEmail]}
/>
<FieldArray name="hobbies" component=
{renderHobbies}/>
<CustomButton buttonLabel={“Back”}
onPress={prevPage}/>
<CustomButton
buttonLabel={“Next”}
onPress={handleSubmit(nextPage)}
/>
</View>
)
}
export default reduxForm({
form: 'register-form',
validate,
destroyOnUnmount : false,
forceUnregisterOnUnmount : true
})(RegisterPageTwo)
import React from 'react'
import { View } from 'react-native'
import { connect } from 'react-redux'
import { Field, formValueSelector,
reduxForm } from 'redux-form'
import { CustomButton, FormInput } from
'components'
import { passwordRequired,
validatePassword } from 'utils/Validations'
let RegisterPageThree =
({handleSubmit,onSubmit,prevPage}) => {
const validateConfirmPassword =
(password) =>
Register/RegisterPageThree.js
The RegisterPageThree component includes
two password fields. Added validation that
both passwords should match.
password && password !==
props.password
? VALIDATE_CONFIRM_PASSWORD
: undefined
return (
<View>
<Field
name="password"
component={FormInput}
placeholder={“Enter Password”}
validate=
{[passwordRequired,validatePassword]}
/>
<Field
name="confirmPassword"
component={FormInput}
placeholder={“Re Enter Password”}
validate=
{[passwordRequired,validateConfirmPassw
ord]}
/>
<CustomButton buttonLabel={“Back”}
onPress={prevPage}/>
<CustomButton buttonLabel={“Next”}
onPress={handleSubmit(nextPage)}/>
</View>
)
}
RegisterPageThree = reduxForm({
form: 'register-form',
destroyOnUnmount : false,
forceUnregisterOnUnmount : true
})(RegisterPageThree)
const selector =
formValueSelector('register-form')
export default RegisterPageThree =
connect(state => {
const password = selector(state, 'password')
return {password}
})(RegisterPageThree)
Register/action.js
export const signupUser = user => ({
type: 'REGISTER_REQUEST',
payload: user,
});
Register/saga.js
import {put, takeLatest} from 'redux-
saga/effects';
import {userSignup} from 'api/Signup';
function* signupUser({payload}) {
try {
const response = yield
userSignup(payload);
yield put({type: 'REGISTER_SUCCESS',
response});
} catch (error) {
yield put({type: 'REGISTER_FAILURE',
error: error.message});
}
}
export default function*
signupScreenSaga() {
yield takeLatest('REGISTER_REQUEST',
signupUser);
}
Explanation
On clicking submit button, onSubmit
will be called, and signupUser(payload)
will be dispatched containing payload.
dispatch(signupUser(payload))
From the file Register/action.js, the
Register action type
“REGISTER_REQUEST” will be
dispatched.
Then saga middleware will watch for
the “REGISTER_REQUEST” type action.
It will take the latest encounter of that
action and call the register API.
For a successful call, it will dispatch the
“REGISTER_SUCCESS” action with
response data.
For a Fail call, it will dispatch the
“REGISTER_FAILURE” action with an
error message.
Update
Reducer
Open store/reducers.js and add this chunk
of code stating switch cases
This reducer serves actions coming from
Login and Register. Both the modules
dispatch similar types of actions-
1. Request Action: Upon this action, the
reducer updates the loading variable to
true.
2. Success Action: Upon this action, the
reducer updates the loading variable to
false and stores the response from the
action to the uservariable.
3. Failure Action: Upon this action, the
reducer updates the loading variable to
false and stores response coming from
action to error variable
const AuthReducer = (state = initialState,
action) => {
switch (action.type) {
case 'REGISTER_REQUEST':
return {
...state,
loading: true,
};
case 'REGISTER_SUCCESS':
return {
...state,
user: action.response,
loading: false,
};
case 'REGISTER_FAILURE':
return {
...state,
error: action.error,
loading: false,
};
store/reducers.js
case 'LOGIN_REQUEST':
return {
...state,
loading: true,
};
case 'LOGIN_SUCCESS':
return {
...state,
user: action.response,
loading: false,
};
case 'LOGIN_FAILURE':
return {
...state,
error: action.error,
loading: false,
};
default:
return state;
}
};
Log In
The Login page accepts two inputs- email
and password.
Login API is called on clicking onSubmit
Button. After successful login Dashboard
screen will appear.
Login/index.js
import React from 'react'
import { Field, reduxForm } from 'redux-
form'
import { useDispatch } from 'react-redux'
import { View, ScrollView } from 'react-
native'
import { loginUser } from './actions'
import { FormInput, CustomButton } from
'components'
import { passwordRequired, emailRequired,
validatePassword , validateEmail } from
'utils/Validations'
const Login = (props) => {
const dispatch = useDispatch()
const onSubmit = (values) =>
dispatch(loginUser(values))
return (
<ScrollView>
<Field
name="email"
component={FormInput}
placeholder={“Enter Email”}
validate={[emailRequired,validateEmail]}
/>
<Field
name="password"
component={FormInput}
placeholder={“Enter Password”}
validate={[passwordRequired,validatePassword]}
/>
<CustomButton
buttonLabel={“Login”}
onPress={props.handleSubmit(onSubmit)}
/>
</ScrollView>
)
}
export default reduxForm({
form: 'login-form'
})(Login)
Login/action.js
export const loginUser = (user) => ({
type: "LOGIN_REQUEST",
payload: user,
});
Login/saga.js
import {put, takeLatest} from 'redux-
saga/effects';
import {userLogin} from 'api/login';
function* loginUser({payload}) {
try {
const response = yield userLogin(payload);
yield put({type: 'LOGIN_SUCCESS',
response});
} catch (error) {
yield put({type: 'LOGIN_FAILURE', error:
error.message});
}
}
export default function* loginScreenSaga() {
yield takeLatest('LOGIN_REQUEST',
loginUser);
}
Explanation
On clicking the submit button, onSubmit
will be called, and loginUser(values) will
be dispatched containing the user email
and password.
const onSubmit = (values) =&gt;
dispatch(loginUser(values))
From the file Login/action.js, the Login
action type “LOGIN_REQUEST” will be
dispatched.
Then saga middleware will watch for
the “LOGIN_REQUEST” type action.
It will take the latest encounter of that
action and call the login API.
For a successful call, it will dispatch the
“LOGIN_SUCCESS” action with
response data.
For a Fail call, it will dispatch the
“LOGIN_FAILURE” action with an error
message.
API Call
const API_KEY = '' //put your key here
const endpoint = {
login :
`https://identitytoolkit.googleapis.com/v1/accou
nts:signInWithPassword?key=${API_KEY}`
}
export const userLogin = async (user) => {
const response = await fetch(endpoint.login,{
method: 'POST',
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify({
email: user.email,
password: user.password,
returnSecureToken: true
})
})
if(!response.ok) throw new Error('Something
Went Wrong!!');
const responseData = await response.json()
return responseData.email
}
api/login/index.js
Dashboard
import React from 'react';
import {useSelector} from 'react-redux';
import {scale, verticalScale} from 'react-
native-size-matters';
import {Text, StyleSheet, SafeAreaView}
from 'react-native';
import Colors from 'utils/Colors';
const DashBoard = () => {
const userEmail = useSelector(state =>
state.Auth.user);
return (
<SafeAreaView style={styles.screen}>
<Text style={styles.hiText}>Hii,
there</Text>
Once you are successfully logged in, you’ll
be redirected to the dashboard page. Here’s
the code for the UI.
Dashboard/index.js
<Text style={styles.name}>{userEmail}
</Text>
</SafeAreaView>
);
};
export default DashBoard;
useSelector() allows you to extract data
from the Redux store state, using a selector
function, so that we can use it in our
component. As you can see, we can get the
value of the user’s email address from
state.Login.user.
You can find the entire source code of the
demo application at Github Repository,
from where you can clone and play around
with code.
Conclusion
So, this was about implementing redux-saga
with your redux-form in React Native
application. We have covered complete
authentication using redux-form features
Field Array, Wizard Form, and redux-
middleware. You can visit the React Native
Tutorials page for more such tutorials and
clone the github repository to experiment.
If you are looking for a helping hand for
your React Native application, please
contact us today to hire React Native
developers from us. We have experienced
and skilled developers having fundamental
and advanced knowledge of React Native.
Thank You
www.bacancytechnology.com

Beginner’s tutorial (part 2) how to integrate redux-saga in react native app

  • 1.
    Beginner’s Tutorial (Part-2): How to Integrate Redux-Sagain React Native App www.bacancytechnology.com
  • 2.
    We have learnedand implemented the basics of redux-form in our previous tutorial: Integrate Redux Form (Part-1). You can visit the tutorial if you don’t have a basic idea of Redux Form or are struggling to use it in your application. Now, it’s time to step up and introduce redux-saga with redux form. Are you looking for a simple tutorial to get started with redux middleware in your react native application? If yes, then you have chosen the correct blog! In this tutorial, we will implement an authentication module in our demo application using redux-saga and redux form.
  • 3.
  • 4.
    Before moving towardsimplementing our authentication module, watch the video below to have a better idea of the demo application.
  • 5.
  • 6.
    Redux-Saga Redux-Form Register Login Dashboard Field Array –Field Array component is used for rendering an array of fields. Wizard Form – The common pattern for separating a single form into different input pages is Wizard. Mainly we will learn about- The demo will contain an Authentication module in which we have used redux-form. The module will have- Use of two redux-form features:
  • 7.
    And also calledFirebase REST API from the Login and Register module. So, we are clear with the requirements and what the demo will contain. Without wasting more time, let’s get started with building our demo application.
  • 8.
  • 9.
    The very firststep will be setting up the store. For connecting the store to your application, open app/index.js app/index.js import { store } from 'store' import { Provider as ReduxProvider } from 'react-redux' export default () => ( <ReduxProvider store={store}> <App/> </ReduxProvider> )
  • 10.
    Individual action.js andsaga.js file for the Register and Login Page (which we will see in the coming sections) A folder named store having three files – index.js, reducers.js, and sagas.js So, now the store is accessible through our entire application. It’s time to use the store in our app. For that, we will need to do two things- store/index. js import createSagaMiddleware from 'redux- saga'; import {createStore, applyMiddleware} from 'redux'; import {combinedReducers} from './reducers'; import rootSaga from './sagas'; const sagaMiddleware = createSagaMiddleware(); const middlewares = [sagaMiddleware];
  • 11.
    const store = createStore(combinedReducers, applyMiddleware(...middlewares)); sagaMiddleware.run(rootSaga); export{store}; store/reducers.js import {combineReducers} from 'redux'; import {reducer as formReducer} from 'redux-form'; export const combinedReducers = combineReducers({ form: formReducer, Auth: AuthReducer, });
  • 12.
    store/sagas.js import {all} from'redux-saga/effects'; import loginScreenSaga from 'screens/Login/saga'; import signupScreenSaga from 'screens/Register/saga'; function* rootSaga() { yield all([loginScreenSaga(), signupScreenSaga()]); } export default rootSaga;
  • 13.
  • 14.
    RegisterPageOne.js RegisterPageTwo.js RegisterPageThree.js We will separatethe Register form into separate pages of inputs named- This pattern of splitting is known as Wizard Form. Register/index.js To separate the form into small forms we will use a state variable- page for keeping track of the page to be rendered. import React, { useState } from 'react’ import { ScrollView } from 'react-native' import RegisterPageOne from './RegisterPageOne' import RegisterPageTwo from './RegisterPageTwo'
  • 15.
    import RegisterPageThree from './RegisterPageThree' constRegister = (props) => { const [page,setPage] = useState(1) const onSubmit = (Values) => console.log(Values) const goToNextPage = () => setPage( page => page + 1 ) const goToPrevPage = () => setPage( page => page - 1 ) return ( <ScrollView> {page === 1 && <RegisterPageOne nextPage= {goToNextPage} />} {page === 2 && <RegisterPageTwo nextPage= {goToNextPage} prevPage={goToPrevPage} />} {page === 3 && <RegisterPageThree onSubmit= {onSubmit} prevPage={goToPrevPage} />} </ScrollView> ) } export default Register
  • 16.
    Register/RegisterPageOne.js RegisterPageOne is ourfirst component which will have two fields : Full Name and User Name. import React from 'react' import { View } from 'react-native' import { Field, reduxForm } from 'redux- form' import { FormInput , CustomButton } from 'components' import { usernameRequired , fullnameRequired } from 'utils/Validations' const RegisterPageOne = ({handleSubmit,nextPage}) => { return ( <View> <Field name="fullName" component={FormInput} validate={[fullnameRequired]}
  • 17.
    placeholder="Enter Full Name" /> <Field name="userName" component={FormInput} validate={[usernameRequired]} placeholder="EnterUser Name" onSubmitEditing = {handleSubmit(nextPage)} /> <CustomButton buttonLabel="Next" onPress={handleSubmit(nextPage)} /> </View> ) } export default reduxForm({ form: 'register-form', destroyOnUnmount: false, forceUnregisterOnUnmount: true })(RegisterPageOne)
  • 18.
    Register/RegisterPageTwo.js RegisterPageTwo is oursecond component having three fields: Mobile No, Email, and Hobbies. The input for hobbies uses the FieldArray API to render multiple inputs to the user. We will also add validation to the input fields. import React from 'react' import { StyleSheet, View , Text } from 'react-native' import { Field, FieldArray, reduxForm } from 'redux-form' import { DeleteButton, CustomButton, FormInput } from 'components' import { emailRequired, mobileNoRequired, validateEmail, validateMobileno } from 'utils/Validations' const renderHobbies = ({ fields, meta : {error , submitFailed } }) => { return(
  • 19.
    <View> <CustomButton buttonLabel={“Add Hobby”} onPress={() =>fields.push({})} /> {fields.map((hobby,index) => ( <View key={index}> <Field name={hobby} placeholder={`Hobby #${index + 1 }`} component={FormInput} /> <DeleteButton onDelete={() => fields.remove(index)} /> </View> ))} { submitFailed && error && <Text>{error} </Text> } </View> ) } const validate = (values,props) => {
  • 20.
    const errors ={} if (!values.hobbies || !values.hobbies.length) errors.hobbies = { _error : “Add at least One hobby” } else{ const hobbiesArrayErrors = [] values.hobbies.forEach((hobby,index)=>{ if (!hobby || !hobby.length) hobbiesArrayErrors[index] = HOBBY_REQUIRED }) if(hobbiesArrayErrors.length) errors.hobbies = hobbiesArrayErrors } return errors } const RegisterPageTwo = ({prevPage,handleSubmit,nextPage}) => { return (
  • 21.
    <View> <Field name="mobileNo" component={FormInput} placeholder={“Enter Mobile Number”} validate= {[mobileNoRequired,validateMobileno]} /> <Field name="email" component={FormInput} placeholder={“Enteremail”} validate={[emailRequired,validateEmail]} /> <FieldArray name="hobbies" component= {renderHobbies}/> <CustomButton buttonLabel={“Back”} onPress={prevPage}/> <CustomButton buttonLabel={“Next”} onPress={handleSubmit(nextPage)} />
  • 22.
    </View> ) } export default reduxForm({ form:'register-form', validate, destroyOnUnmount : false, forceUnregisterOnUnmount : true })(RegisterPageTwo)
  • 23.
    import React from'react' import { View } from 'react-native' import { connect } from 'react-redux' import { Field, formValueSelector, reduxForm } from 'redux-form' import { CustomButton, FormInput } from 'components' import { passwordRequired, validatePassword } from 'utils/Validations' let RegisterPageThree = ({handleSubmit,onSubmit,prevPage}) => { const validateConfirmPassword = (password) => Register/RegisterPageThree.js The RegisterPageThree component includes two password fields. Added validation that both passwords should match.
  • 24.
    password && password!== props.password ? VALIDATE_CONFIRM_PASSWORD : undefined return ( <View> <Field name="password" component={FormInput} placeholder={“Enter Password”} validate= {[passwordRequired,validatePassword]} /> <Field name="confirmPassword" component={FormInput} placeholder={“Re Enter Password”} validate= {[passwordRequired,validateConfirmPassw ord]} />
  • 25.
    <CustomButton buttonLabel={“Back”} onPress={prevPage}/> <CustomButton buttonLabel={“Next”} onPress={handleSubmit(nextPage)}/> </View> ) } RegisterPageThree= reduxForm({ form: 'register-form', destroyOnUnmount : false, forceUnregisterOnUnmount : true })(RegisterPageThree) const selector = formValueSelector('register-form') export default RegisterPageThree = connect(state => { const password = selector(state, 'password') return {password} })(RegisterPageThree)
  • 26.
    Register/action.js export const signupUser= user => ({ type: 'REGISTER_REQUEST', payload: user, }); Register/saga.js import {put, takeLatest} from 'redux- saga/effects'; import {userSignup} from 'api/Signup'; function* signupUser({payload}) { try { const response = yield userSignup(payload); yield put({type: 'REGISTER_SUCCESS', response}); } catch (error) { yield put({type: 'REGISTER_FAILURE',
  • 27.
    error: error.message}); } } export defaultfunction* signupScreenSaga() { yield takeLatest('REGISTER_REQUEST', signupUser); } Explanation On clicking submit button, onSubmit will be called, and signupUser(payload) will be dispatched containing payload. dispatch(signupUser(payload))
  • 28.
    From the fileRegister/action.js, the Register action type “REGISTER_REQUEST” will be dispatched. Then saga middleware will watch for the “REGISTER_REQUEST” type action. It will take the latest encounter of that action and call the register API. For a successful call, it will dispatch the “REGISTER_SUCCESS” action with response data. For a Fail call, it will dispatch the “REGISTER_FAILURE” action with an error message.
  • 29.
  • 30.
    Open store/reducers.js andadd this chunk of code stating switch cases This reducer serves actions coming from Login and Register. Both the modules dispatch similar types of actions- 1. Request Action: Upon this action, the reducer updates the loading variable to true. 2. Success Action: Upon this action, the reducer updates the loading variable to false and stores the response from the action to the uservariable. 3. Failure Action: Upon this action, the reducer updates the loading variable to false and stores response coming from action to error variable
  • 31.
    const AuthReducer =(state = initialState, action) => { switch (action.type) { case 'REGISTER_REQUEST': return { ...state, loading: true, }; case 'REGISTER_SUCCESS': return { ...state, user: action.response, loading: false, }; case 'REGISTER_FAILURE': return { ...state, error: action.error, loading: false, }; store/reducers.js
  • 32.
    case 'LOGIN_REQUEST': return { ...state, loading:true, }; case 'LOGIN_SUCCESS': return { ...state, user: action.response, loading: false, }; case 'LOGIN_FAILURE': return { ...state, error: action.error, loading: false, }; default: return state; } };
  • 33.
  • 34.
    The Login pageaccepts two inputs- email and password. Login API is called on clicking onSubmit Button. After successful login Dashboard screen will appear. Login/index.js import React from 'react' import { Field, reduxForm } from 'redux- form' import { useDispatch } from 'react-redux' import { View, ScrollView } from 'react- native' import { loginUser } from './actions' import { FormInput, CustomButton } from 'components' import { passwordRequired, emailRequired, validatePassword , validateEmail } from 'utils/Validations' const Login = (props) => {
  • 35.
    const dispatch =useDispatch() const onSubmit = (values) => dispatch(loginUser(values)) return ( <ScrollView> <Field name="email" component={FormInput} placeholder={“Enter Email”} validate={[emailRequired,validateEmail]} /> <Field name="password" component={FormInput} placeholder={“Enter Password”} validate={[passwordRequired,validatePassword]} /> <CustomButton buttonLabel={“Login”} onPress={props.handleSubmit(onSubmit)} /> </ScrollView> ) } export default reduxForm({ form: 'login-form' })(Login)
  • 36.
    Login/action.js export const loginUser= (user) => ({ type: "LOGIN_REQUEST", payload: user, }); Login/saga.js import {put, takeLatest} from 'redux- saga/effects'; import {userLogin} from 'api/login'; function* loginUser({payload}) { try { const response = yield userLogin(payload); yield put({type: 'LOGIN_SUCCESS', response}); } catch (error) { yield put({type: 'LOGIN_FAILURE', error: error.message});
  • 37.
    } } export default function*loginScreenSaga() { yield takeLatest('LOGIN_REQUEST', loginUser); } Explanation On clicking the submit button, onSubmit will be called, and loginUser(values) will be dispatched containing the user email and password. const onSubmit = (values) =&gt; dispatch(loginUser(values))
  • 38.
    From the fileLogin/action.js, the Login action type “LOGIN_REQUEST” will be dispatched. Then saga middleware will watch for the “LOGIN_REQUEST” type action. It will take the latest encounter of that action and call the login API. For a successful call, it will dispatch the “LOGIN_SUCCESS” action with response data. For a Fail call, it will dispatch the “LOGIN_FAILURE” action with an error message.
  • 39.
  • 40.
    const API_KEY ='' //put your key here const endpoint = { login : `https://identitytoolkit.googleapis.com/v1/accou nts:signInWithPassword?key=${API_KEY}` } export const userLogin = async (user) => { const response = await fetch(endpoint.login,{ method: 'POST', headers: { 'Content-Type' : 'application/json' }, body: JSON.stringify({ email: user.email, password: user.password, returnSecureToken: true }) }) if(!response.ok) throw new Error('Something Went Wrong!!'); const responseData = await response.json() return responseData.email } api/login/index.js
  • 41.
  • 42.
    import React from'react'; import {useSelector} from 'react-redux'; import {scale, verticalScale} from 'react- native-size-matters'; import {Text, StyleSheet, SafeAreaView} from 'react-native'; import Colors from 'utils/Colors'; const DashBoard = () => { const userEmail = useSelector(state => state.Auth.user); return ( <SafeAreaView style={styles.screen}> <Text style={styles.hiText}>Hii, there</Text> Once you are successfully logged in, you’ll be redirected to the dashboard page. Here’s the code for the UI. Dashboard/index.js
  • 43.
    <Text style={styles.name}>{userEmail} </Text> </SafeAreaView> ); }; export defaultDashBoard; useSelector() allows you to extract data from the Redux store state, using a selector function, so that we can use it in our component. As you can see, we can get the value of the user’s email address from state.Login.user. You can find the entire source code of the demo application at Github Repository, from where you can clone and play around with code.
  • 44.
  • 45.
    So, this wasabout implementing redux-saga with your redux-form in React Native application. We have covered complete authentication using redux-form features Field Array, Wizard Form, and redux- middleware. You can visit the React Native Tutorials page for more such tutorials and clone the github repository to experiment. If you are looking for a helping hand for your React Native application, please contact us today to hire React Native developers from us. We have experienced and skilled developers having fundamental and advanced knowledge of React Native.
  • 46.