React Native Redux for API Response
Dependencies Required:
Redux
A central store for state management that can be used throughout the app to store and fetch data from. It is a predictable state container for JavaScript apps and helps you write applications that behave consistently, run in different environments, and are easy to test.
Redux can be installed using below command.
npm install --save redux
Redux Toolkit
Redux Toolkit can be installed using below command.
npm install @reduxjs/toolkit
Redux Thunk
This library makes the actions of redux asynchronous. It is a middleware for Redux and can be used well for async actions such as HTTP requests.
Redux Thunk can be installed using below command.
npm install redux-thunk
Redux Logger
This library is a middleware for Redux and is used to track whats happening in Redux displaying logs on the same.
Redux Logger can be installed using below command.
npm install redux-logger
Axios
It’s a promise based http client to make api calls inside the app.
Axios can be installed using below command.
Example
Reducer.js File
import ACTION_TYPES from './ActionTypes'; | |
const initialState = { | |
data: '', | |
error: '' | |
}; | |
const apiReducer = (state = initialState, action) => { | |
switch (action.type) { | |
case ACTION_TYPES.API_SUCCESS: | |
return { | |
...state, | |
data: action.payload | |
}; | |
case ACTION_TYPES.API_ERROR: | |
return { | |
...state, | |
error: action.payload | |
}; | |
default: | |
return state; | |
} | |
}; | |
export default apiReducer; |
Action.js
import ACTION_TYPES from './ActionTypes.js'; | |
export const fetchSuccess = data => ({ | |
type: ACTION_TYPES.API_SUCCESS, | |
payload: data | |
}); | |
export const fetchError = error => ({ | |
type: ACTION_TYPES.API_ERROR, | |
payload: error | |
}); |
ActionCreator.js
import axios from 'axios'; | |
import {fetchSuccess, fetchError } from "./Action"; | |
const actionCreator = url => { | |
return dispatch => { | |
return new Promise(() => { | |
console.log("url", url) | |
axios.get(url) | |
.then((resp) => { | |
if(resp!=null && resp.data!=null) | |
dispatch(fetchSuccess(resp.data)); | |
}) | |
.catch((err) => { | |
dispatch(fetchError(err)); | |
}) | |
}) | |
}; | |
}; | |
export default actionCreator; | |
Store.js
A store holds the whole state tree of your application, createStore is used to create the store. The only way to change the state inside it is to dispatch an action on it.
Here applyMiddleware is used to utilise middleware such as redux-thunk and redux logger.
import { createStore, applyMiddleware, compose, combineReducers } from 'redux'; | |
import thunk from 'redux-thunk'; | |
import { createLogger } from 'redux-logger'; | |
import apiReducer from './Reducer'; | |
const appReducers = combineReducers({ | |
apiReducer, | |
}); | |
const rootReducer = (state, action) => appReducers(state, action); | |
const logger = createLogger(); | |
let middleware = []; | |
middleware = [...middleware, thunk], logger; | |
export default createStore( | |
rootReducer, | |
compose(applyMiddleware(...middleware)) | |
); |
HomeScreen.js
import React, { useState, useEffect } from 'react'; | |
import { StyleSheet, View, Text, TouchableOpacity, StatusBar, FlatList, SafeAreaView } from 'react-native'; | |
import apiCall from "../redux/ActionCreator"; | |
import { useDispatch, useSelector } from "react-redux"; | |
const HomeSCreen = () => { | |
const [isLoaded, setLoaded] = useState(false) | |
const [usersList, setUsers] = useState([]) | |
// to dispatch action and call the API | |
const dispatch = useDispatch(); | |
function loadAPI() { | |
dispatch(apiCall(production.fetchUsers)) | |
} | |
// to get the response from redux | |
const responseList = useSelector(state => { | |
return state.apiReducer.data.data | |
}) | |
useEffect(() => { | |
if (!isLoaded) { | |
loadAPI(); | |
setLoaded(true) | |
} | |
}, | |
[]); | |
return ( | |
<View style={styles.backgroundImage}> | |
<FlatList style={{ | |
backgroundColor: '#F0F5F9', | |
width: "100%", | |
}} | |
data={responseList} | |
renderItem={ | |
({ item }) => ( | |
//item of the array fetched from redux | |
)} | |
keyExtractor={(item, index) => index.toString()} | |
/> | |
</View> | |
); | |
} | |
export default HomeSCreen; | |
}); | |
Hope this helped you!!
2 Comments
ReplyDeleteVery Informative and creative contents. This concept is a good way to enhance the knowledge. thanks for sharing.
Continue to share your knowledge through articles like these, and keep posting more blogs.
And more Information React native for mobile application development
Glad that it is helpful. Thanks for liking it :)
Delete