Updated 31 July 2020
In this blog, I am describing How to call the Web Service API and How can use a response in Redux? In my previous blog, I have described the concept, feature, and work of Redux.
If you not aware workflow of Redux please look at once. https://mobikul.com/react-native-redux/
this tutorial will help you to understand how asynchronous actions work since the previous tutorial was based on synchronous actions any web service calls cannot be done due to the functions were pure.
Async Actions:
When a call is dispatched to an async action there are two vital stages that need to be considered. The start of the action dispatch & the point of receiving a response. In order to tackle the above-mentioned scenario’s three actions must be defined as mentioned below.
1. Action to inform about the start action call
When an action is dispatched on the start of the action call it can update the state through a flag which will inform the UI to show a loading spinner.
2. Action to inform the dispatched action completed successfully
With the successful completion of the dispatched function, the reducer can update the state with the response data and reset the loader spinning flag to be hidden from the UI.
3. Action to inform the dispatched action failed.
Through this action, the reducer can be updated to update the loading spinner flag and any error from the API response that can be displayed on the UI.
The action for the service call will be accompanied by three action type methods which will be dispatched on the three scenarios as described above with another method to execute the actual service call which has been defined in the mapDispatchedToProps method that is provided by Redux.
The action for the service call will be written as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const startingCallAPI = ()=>( { type:"API_STARTED", payload :true}); const successResponse = ( data)=> ( {type:"API_BUTTON_CLICK_RESPONSE", "payload":data}); const errorResponse = (data)=> ( {type:"API_BUTTON_ERROR_RESPONSE", "payload":{message:data}}); export const getLoginDataFromAPI = (url, body)=>{ return dispatch=>{ dispatch(startingCallAPI()); fetchAPICall(url, "POST", body).then(response => { if(response.user_info){ dispatch(successResponse(response)) }else{ dispatch( errorResponse(response.message)); } }) } } |
As shown above, within the getLoginDataFromAPI method three action types have been dispatched for each response from on start until a response is received irrespective of success or error and thereby the reducer will update the status accordingly which is shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import { combineReducers } from "redux"; import CovidModel from "../store/CovidModel"; const INITIAL_COVID_STATE = { citizesVisible : false, loginResns : [], isUpdate:false, progresponse : {} } const covidReducer = (state=INITIAL_COVID_STATE, action)=>{ const {citizens, isUpdate, progressVisible, loginResponse} = state; switch (action.type) { case "ADD": citizens.push(action.payload); return {citizens, isUpdate}; case "UPDATE": let isUpdating = !isUpdate return {citizens, isUpdate : isUpdating}; case "API_STARTED": return {progressVisible : true, loginResponse} case "API_BUTTON_CLICK_RESPONSE": return {progressVisible : false, loginResponse:action.payload } case "API_BUTTON_ERROR_RESPONSE": return {progressVisible : false,loginResponse:action.payload } default: return state; } } export default combineReducers({ covidList : covidReducer }) |
As shown above for each action that is dispatched the state is updated accordingly to notify the UI Components. If no action is dispatched a default state is returned to comprehend with the UI.
“Redux middleware solves different problems than Express or Koa middleware, but in a conceptually similar way. It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more.”
for more – https://redux.js.org/advanced/async-actions
Now We need Middleware
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.
installation
1 |
npm install redux-thunk |
Redux Logger
As the name indicates, it’s a logging tool middleware for redux. This library helps you to track down what’s happening with redux while developing your app. Install redux logger using the following command:
1 |
npm i –save redux-logger |
“applyMiddleware”: with the help of this component provided by redux the above middleware’s can be bound to the application.
“compose”: is used when multiple store components need to be applied to increase the functionality of the store itself such as the redux-thunk & redux-logger.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import { createStore, applyMiddleware, compose, } from 'redux'; import { createLogger } from 'redux-logger'; import CovidReducer from './src/reducer/CovidReducer'; import CovidContainer from './src/navigation/CovidNavigation'; const logger = createLogger(); const covidStore = createStore( rootReducer, compose(applyMiddleware(...middleware)) ); <Provider store={covidStore}> <CovidContainer/> </Provider> |
Now Bellow the code for the user the store and dispatch an action to our created getLoginDataFromAPI
1 2 3 4 5 6 7 8 9 10 |
const mapDispatchToProps = dispatch => ( { getLoginDataFromAPI : (url, body)=> dispatch(getLoginDataFromAPI(url, body)) } ); export default connect(mapStateToProps, mapDispatchToProps)(LoginPage); const mapStateToProps = (state) => { const { loginResponse, progressVisible, } = state return { loginResponse, progressVisible, } ;} |
Now Bellow snippet of code for calling an action when login button Click
1 |
this.props.getLoginDataFromAPI(url , body); |
In My Next Blog, I will describe the API middleware Redux-SAGA
Reference Links-
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.