React Native Developer

Friday, February 5, 2021

how to use redux-saga in react native , How to loadin API data in React-Native with redux-saga,


PC INFOTECH


redux-saga

Redux-saga is a library that aims to make application side effects easier to handle, more effective to execute, easier to test, and better at handling failures (i.e. asynchronous things such as data fetching and impure things such as accessing the browser cache).


Getting started

Install

$ npm install --save redux-saga

or

$ yarn add redux-saga

 Example

index.js

import React from 'react';
import {AppRegistry} from 'react-native';
import {name as appName} from './app.json';
import Store from './src/redux/store';
import {Provider} from 'react-redux';
import App from './App';

const screen = () => (
<Provider store={Store}>
<App />
</Provider>
);
AppRegistry.registerComponent(appName, () => screen);

console.disableYellowBox = true;

src/store.js

  • create a Saga middleware with a list of Sagas to run (so far we have only one helloSaga)
  • connect the Saga middleware to the Redux store
import {createStore, compose, applyMiddleware} from 'redux';
import createSagaMiddleware from 'redux-saga';
import {createLogger} from 'redux-logger';
import reducers from './reducers/rootReducers';
import rootSaga from './sagas';
const middleWare = [];

const loggerMiddleware = createLogger({
predicate: () => process.env.NODE_ENV === 'development',
});
middleWare.push(loggerMiddleware);

const sagaMiddleware = createSagaMiddleware();
middleWare.push(sagaMiddleware);

const store = createStore(
reducers,
{},
compose(applyMiddleware(...middleWare)),
);
sagaMiddleware.run(rootSaga);

export default store;



src/redux/sagas/rootSaga

import {fork} from 'redux-saga/effects';
import watchFetchUser from './saga';

export default function* rootSaga() {
yield fork(watchFetchUser);
}


src/redux/sagas/saga.js

import {FETCHED_USER, USER_DETAILS_REQUEST} from '../actions/actionType';
import {takeEvery, takeLatest} from 'redux-saga/effects';
import {getUserDetails} from '../actions/index';

export const fetchUser = () => {
return {type: FETCHED_USER};
};

export function* watchFetchUser() {
yield takeLatest(FETCHED_USER, getUserDetails);
}

export default watchFetchUser;


src/redux/action/index.js

import {
USER_DETAILS_REQUEST,
USER_DETAILS_SUCCESS,
USER_DETAILS_FAILURE,
} from './actionType';
import {GET, GetApi} from '../actions/apisBase';
import {_getUserDetails} from '../../service';
import {put, call} from 'redux-saga/effects';

export function* getUserDetails() {
try {
yield put({type: USER_DETAILS_REQUEST});
const user = yield call(GET, {url: _getUserDetails});
console.log(':: user response ::', user),
yield put({
type: USER_DETAILS_SUCCESS,
user: user,
});
} catch (error) {
console.log(':: response error ::', error);
yield put({
type: USER_DETAILS_FAILURE,
});
}
}



src/redux/actions/apiBase.js

import axios from 'axios';
import {_getUserDetails} from '../../service/index';

export const GET = async ({url, body}) => {
console.log('url', url);
console.log('body', body);
try {
const response = await axios.get(url, {});
console.log('get', response.data);
return response.data;
} catch (error) {
return console.log('error :: ', error);
}
};


src/redux/actions/actionTypes.js

export const USER_DETAILS_REQUEST = 'USER_DETAILS_REQUEST';
export const USER_DETAILS_SUCCESS = 'USER_DETAILS_SUCCESS';
export const USER_DETAILS_FAILURE = 'USER_DETAILS_FAILURE';

export const FETCHED_USER = 'FETCHED_USER';

src/redux/reducers/index.js


const
initialState = {
isLoading: false,
user: [],
};
export default function App(state = initialState, action) {
console.log('action:::', action);
switch (action.type) {
case 'USER_DETAILS_REQUEST':
return {
...state,
isLoading: true,
};
case 'USER_DETAILS_SUCCESS':
return {
...state,
isLoading: false,
user: action.user,
};
case 'USER_DETAILS_FAILURE':
return {
...state,
isLoading: false,
};
default:
return state;
}
}


src/redux/reducers/rootReducers.js

import {combineReducers} from 'redux';
import App from './index';

export default combineReducers({
userDetails: App,
});

src/screen/userDetails.js

import React from 'react';
import {
View,
Text,
StyleSheet,
Dimensions,
TouchableOpacity,
Image,
} from 'react-native';
const {width} = Dimensions.get('window');
const userDetails = ({item, index}) => {
return (
<TouchableOpacity style={styles.container}>
<View style={{flexDirection: 'row'}}>
<Image source={{uri: item.avatar}} style={styles.imageStyle} />
<View style={styles.textCoverView}>
<Text style={styles.commonTextStyle}>
<Text children={'Name : '} style={styles.textStyle} />
{item.first_name} {item.last_name}
</Text>
<Text style={styles.commonTextStyle}>
<Text children={'Email : '} style={styles.textStyle} /> {item.email}
</Text>
</View>
</View>
</TouchableOpacity>
);
};

const styles = StyleSheet.create({
container: {
padding: 10,
margin: 5,
backgroundColor: '#d3d3d3',
width: '96%',
justifyContent: 'center',
alignSelf: 'center',
borderRadius: 10,
},
imageStyle: {
width: width * 0.2,
height: width * 0.2,
borderRadius: (width * 0.2) / 6,
},
textCoverView: {
marginLeft: (width * 0.2) / 5,
},
commonTextStyle: {
fontSize: (width * 0.2) / 5,
},
textStyle: {
color: '#fff',
fontWeight: 'bold',
fontSize: (width * 0.2) / 5,
},
});

export default userDetails;

app.js

import React, {useState, useEffect} from 'react';
import {View, FlatList, StyleSheet, Text, Platform} from 'react-native';
import {useSelector, useDispatch} from 'react-redux';
import UserDetails from './src/screen/userDetails';
import {getUserDetails} from './src/redux/actions/index';
import {fetchUser} from './src/redux/sagas/saga';
const App = (props) => {
const userData = useSelector((state) => state.userDetails.user.data);
const dispatch = useDispatch();

useEffect(() => {
dispatch(fetchUser());
}, []);

return (
<View style={styles.container}>
<FlatList
data={userData}
keyExtractor={(item, index) => index.toString()}
renderItem={({item, index}) => {
return <UserDetails item={item} />;
}}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: Platform.OS === 'ios' ? 35 : 0,
},
});
export default App;

src/services/index.js

const BASE_URL = 'https://reqres.in/api/';

export const _getUserDetails = BASE_URL + 'users?page=1';
export const _getDetails = BASE_URL + 'unknown';








Thank You !



2 comments:

  1. Thanks, Paresh Chavda

    You help me a lot.

    ReplyDelete
  2. Appsinvo is the Mobile App Development Company. With the help of our team passion and hard work we have come a long way and many milestones are still to achieve in the coming days.
    Top Mobile App Development Company
    Top Mobile App Development Company in India

    ReplyDelete