Redux is a standalone state management library, which can be used with any library or framework. If your background is React developer, then you have used the Redux library with React. The primary use of Redux is that we can use one application state as a global state and interact with the state from any react component is very easy whether they are siblings or parent-child. Now, let us start the React Native Redux Example Tutorial by installing React Native on Mac first.

Start implement Redux in React Native 

  • Creating New Project run this command
react-native init <Project-name>
  • After then create a project add node package
npm install --save native-base react-native-elements redux react-redux axios redux-thunk redux-logger
  • After then install node package then run this command
react-native link
  • After then Open  index.js  under Project folder and add this code.
import {AppRegistry} from 'react-native';
import App from './src/App';
import {name as appName} from './app.json';
import React from 'react';
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import reducer from './src/Reducers/index'
import thunk from 'redux-thunk';
import logger from 'redux-logger'
const store = createStore(reducer, applyMiddleware(thunk, logger));
const reactNativeRedux = () => (
   <Provider store = { store }>
      <App />
   </Provider>
)
AppRegistry.registerComponent(appName, () => reactNativeRedux);
  • After then create Constants folder create and create  ActionTypes.js file under the folder then add code
export const NAME_LIST = 'NAME_LIST'
export const NAME_CREATE = "NAME_CREATE"
export const NAME_EDIT = 'NAME_EDIT'
export const NAME_DELETE = 'NAME_DELETE'
  • After then create Actions folder create and create ActionTypes.js file under the folder then add code
import * as types from '../Constants/ActionTypes';
const url = 'http://localhost:8888/'
import axios from './node_modules/axios';
export function namelist(){
return function(dispatch) {
var headers = {
'Content-Type': 'application/json',
}
axios.post(url+'api/getNames', {}, {headers: headers}).then(function (response) {
dispatch({
type: types.NAME_LIST,
payload: response.data.data
});
}).catch(function (error) {
dispatch({
type: types.NAME_LIST,
payload: []
});
});
}
}
export function addName(data){
return function(dispatch) {
var headers = {
'Content-Type': 'application/json',
}
axios.post(url+'api/addName', {name:data}, {headers: headers}).then(function (response) {
dispatch({
type: types.NAME_CREATE,
payload: "Added!"
});
}).catch(function (error) {
dispatch({
type: types.NAME_CREATE,
payload:[]
});
});
}
}
export function editUser(){
return {
type:types.NAME_EDIT,
payload:[]
}
}
export function deleteUser(){
return {
type:types.NAME_DELETE,
payload:[]
}
}
  • After then create Reducers folder create and create two file index.js  and nameReducer.js under the folder then add code

nameReducer.js

export default function (state = {}, action) {
switch(action.type){
case 'NAME_LIST':
return { ...state, nameList:action.payload}
case 'NAME_CREATE':
return { ...state, nameCreate:action.payload}
case 'NAME_EDIT':
return { ...state, nameEdit:action.payload}
case 'NAME_DELETE':
return { ...state, nameDelete:action.payloade}
default :
return state;
}
}

index.js

import {combineReducers} from './node_modules/redux';
import Name from './nameReducer'
const rootReducer = combineReducers({
Name
})
export default rootReducer;
  • After that open App.js and add this code
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Alert} from 'react-native';
import { Container, Header, Content, Form, Item, Input, Label, Button, List, ListItem, Left } from 'native-base';
import {connect} from 'react-redux';
import {bindActionCreators}from 'redux';
import { namelist, addName } from './Actions';
class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
        name:''
      }
  }
async componentDidMount () {
   await this.props.namelist();
}
validateName = (value, type) =>{
   if(value!='' || value!=undefined || value!=null){
     this.setState({name:value});
   }else{
     Alert.alert("Enter name");
   }
}
addItemname = async() =>{
   await this.props.addName(this.state.name);
   await this.props.namelist();
}
render() {
return (
<Container>
<Header />
<Content>
<Form>
<Item floatingLabel>
<Label>Add name</Label>
<Input name="name" onChangeText={(text) => this.validateName(text, 'name')} />
</Item>
</Form>
<Button onPress={() => this.addItemname()} full success>
<Text>Add</Text>
</Button>
<List>
{this.props.namedata?this.props.namedata.map((item, index)=> (
<ListItem key={item._id} noIndent style={{ backgroundColor: "#cde1f9" }}>
<Left>
<Text>{item.name}</Text>
</Left>
</ListItem>
)):null}
</List>
</Content>
</Container>
);
}
}
const mapStateToProps = (state) => {
 return {
    namedata: state.Name.nameList
 }
}
const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({
    namelist, addName
  },dispatch)
}
export default connect(mapStateToProps,mapDispatchToProps)(App);

React native implement Redux Done.

Run command

react-native run-android
react-native run-ios

if you are change the App name then you delete android and ios folder of you project. After then run this command

 react-native eject

this command help to create android and ios folder with clean status
 

Thank you

Github link: https://github.com/Sudarshan101/React-Native-Redux-Nodejs-MongoDB

Youtube : https://www.youtube.com/watch?v=ukLAOKtccq4

About the author
Code solution

info@codesolution.co.in

Discussion
  • 0 comments

Add comment To Login
Add comment