0% found this document useful (0 votes)
153 views7 pages

Redux Async - Course Introduction: Let Us First Try To Understand The Asynchronous Behaviour!

The document provides an introduction to handling asynchronous behavior in Redux applications. It discusses asynchronous actions, middleware like Redux Thunk that allow asynchronous API calls, and how to create thunks. It provides examples of asynchronous "Hello World" implementations using thunk to dispatch actions with delays. The document also explains concepts like asynchronous action types, middleware, and how Redux Thunk works by returning functions that receive the dispatch as an argument.

Uploaded by

Mahesh VP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
153 views7 pages

Redux Async - Course Introduction: Let Us First Try To Understand The Asynchronous Behaviour!

The document provides an introduction to handling asynchronous behavior in Redux applications. It discusses asynchronous actions, middleware like Redux Thunk that allow asynchronous API calls, and how to create thunks. It provides examples of asynchronous "Hello World" implementations using thunk to dispatch actions with delays. The document also explains concepts like asynchronous action types, middleware, and how Redux Thunk works by returning functions that receive the dispatch as an argument.

Uploaded by

Mahesh VP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Redux Async - Course Introduction

In this course we will be discussing:

 Asynchronous behaviour in applications


 Redux Middleware for handling asynchronous actions
 Dive deep into the Redux Library Thunk
 Create thunks and link them to the stores.

Asynchronicity Explained

Let us first try to understand the asynchronous behaviour!

Consider an e-commerce application that displays products frequently bought together,


customers buying the product and the customer reviews corresponding to the
product.

Each of these details are served by different API's and time taken to return the results can be
different. Making asynchronous calls to each of these APIs allow displaying the details on
the page without waiting for all the calls to get completed.

Asynchronicity Decoded!
Did you note something different in our Example Application?

The final data chunks took time before being available to user! The asynchronicity that arises
after submitting data is handled by Redux in an excellant manner.

Let us explore it!

Handling Asynchronous Actions in Redux


Redux-thunk and Redux-saga are middleware (higher order functions) that are used to
make asynchronous API calls in Redux.

We will explore more on both the middleware in the upcoming modules.

Asynchronous Action explained


To start with, let us write a Redux function() that dispatches an action of type
"GET_DETAILS".
export const sinFunction = () => (dispatch, getState) => {
dispatch({
type: GET_DETAILS
})
setTimeout(() => {
dispatch({
type: CANCEL_FETCH
})
}, 2000)
}

Please note that dispatch of the action CANCEL_FETCH is delayed by 2000 ms/ 2sec. Thus,
making it possible to control when and how the developer can dispatch the action.

Important Actions in Async


Calling an asynchronous API (Application Program Interface) involves certain crucial
moments. These momments should be dealt with appropriate action types. When an
asynchronous API call is initiated, there will be a certain time duration that lapses before
receiving the result. This process is dealt with following actions:

 Beginning of the request


 Successful completion of the request
 Failing of the request

Action type Standards


For different kinds of status, appropriate action types should be used to avoid errors,as the
application becomes complex.

For example:

{ type: 'GET_REQUEST' }
{ type: 'GET_REQUEST_FAIL', error: 'Request failed' }
{ type: 'GET_REQUEST_SUCCESS', response: { ... } }

Asynchronous "Hello world!"


It is time to get traditional! Let's take a look at the classic example "hello world" with
an asynchronous action:

Examine the Pen https://codepen.io/anon/pen/OmRRQJ for the complete code for the first
Redux app with asynchronous action.

document.getElementById('delayedHello').addEventListener('click', function () {
setTimeout(function () {
store.dispatch({ type: 'DELAYED_HELLO' })
}, 3000)
})

Here you can notice that the action is dispatched with a delay of 3 seconds, thus making it
asynchronous.

Try it Out - Asynchronous Actions


Create a function which is triggered on the click of a button, and displays "2" with a delay
of 3000ms/ 3 sec.

Use Codepen Playground

Middleware in Redux
The examples covered so far in the Redux State Management course, have
implemented synchronous actions, that returned the new state, but did not 'modify' the global
state.

In the real world scenario, it becomes necessary to


amalgamate reducers with asynchronous behaviour. This is where middleware comes into
the picture!

In Redux, using middleware, synchronous action creators with network request can be


dispatched.

What is Middleware?
Middleware can be seen as software gums that make software development easy, by
composing functionalities. Middleware functions enable developers to design action
creators which return another function.

If the designed criteria is fulfilled, the dispatch of the action can be delayed or an actioncan


be dispatched. The asynchronous Hello World is an example of delaying the dispatch.
A conditional dispatch can be demonstrated by using conditional statements.

Redux Thunk
The name "Thunk" is inspired from the word think!

Thunks can be vizualised as sequence of program instructions packaged as an unit which


get created automatically, to help/ call another sequence of program/ unit.

Installing Thunk
Before exploring middleware , we need to install the package redux-thunk and enable
in store.

For Installing:

npm install --save redux-thunk

For enabling the thunk in store, we will be using the store enhancer applyMiddleware and


pass thunk as an argument:

import { createStore, applyMiddleware } from 'redux';


import thunk from 'redux-thunk';

const store = createStore(


rootReducer,
applyMiddleware(thunk)
);

Dispatching action using Thunk


The value returned by inner function will act as the return value of dispatch. Let us try
to dispatch a function instead of an action.

Once Redux Thunk middleware is enabled, on dispatching, the middleware will call the


same function with dispatch method.

The following example should further clarify the concept:

//enabling thunk as same in previous example


store.dispatch(function (dispatch) {
dispatch({ type: 'actionA' })
setTimeout(() => {
dispatch({ type: 'actionB' })
}, 1000)
})

Hands On Implementing Thunk


Create Actions, Reducers and Store for a Stopwatch timer with a button click eventfor
starting and stopping the time. Use Redux-Thunk for this exercise.

Example using Thunk


Consider an example of data request, where action creator named "getData" is called.

export function getData() {


const request = example.get('http://example.com');
return (dispatch) => {
request.then(({data}) => {
dispatch({ type: 'GET_DATA', payload: data})
});
};
}

Here:

 A request to an existing API is called.


 Since this is a thunk, a function is returned.
 Now a request is made that takes time to be resolved
 As soon as the data is received, a dispatch method which consists of actions is
called.

Custom arguments
Custom argument in thunk can be injected using "withExtraArgument" function.

const store = createStore(


reducer,
applyMiddleware(thunk.withExtraArgument(api))
)
function fetchUser(id) {
return (dispatch, getState, api) => {
}
}

Chatbot implentation using Thunk


Here is an example of a chatbot created using Thunk: http://codepen.io/anon/pen/KmavQK .

This pen covers the basics that we learnt during the course.

Key Highlights:

 The chatbot discussed here has basic features of a chat robot.


 It can recognise user input and respond accordingly.
 Chatting session can be continued for a long time.
 Chatbot is asynchronous.
 By enhancing the dictionary, response quality of the chatbot can be enhanced.

Redux Async - Course Summary


In this course, you learned asynchronous action, middleware and thunk in Redux.

Fork the pens shared through out the course and try to improve the applications for a better
understanding of the concepts you have gone through in this course.

The most widely used Redux middleware - Saga will be covered in a separate course.

Quiz:
1. Redux middleware is responsible for mainly handling __ asynchornus
2. General action creators are function which return__ an action
3. Redux thunk is used to make__ asynchornous API
4. Middleware is basically__ Both
5. Based on the hands on card “MLR Hands On” What is the P>|t| value for the 'INDUS' variable ? 0,731
6. When an asynchronous API is called, it requires a change in the state of application. T
7. What is “setTimeout” method used for? CALL A FUNC
8. Based on the hands on card “MLR Hands On” What is the value of the estimated coef for the constant
term ? 36,4
9. Based on the hands on card “MLR Hands On” Perform a correlation among all the independent
variables . What is the correlation between variables NOX and DIS ? 0,769
10. Middleware is__ BOTH
11. Asynchronous actions can define BOTH
12. Middleware are responsible for making API calls T
13. Action creators which have asynchronous behaviour dispatch actions__ AFTER THEY RECEIVE A RESULT
14. Based on the hands on card “MLR Hands On” What is the standard error for the constant term ? 5,104
15. When an asynchronous API is called, it requires a change in the state of application. T
16. Based on the hands on card “MLR Hands On” what is the value of R sq ? 0,741
17. Once the Redux Thunk middleware is enabled WE CAN....
18. What is Thunk? ALL
19. While making an API call, which of these is preferred? USE MULTIPLE
20. For an API request, which of the following action is dispatched first? REQUEST BEGAN
21. import { createStore, applyMiddleware } from 'redux'; is used for__ ENABLEING
22. Thunk installation is done with following command : NPM-INSTALL
23. For more complex asynchronous actions, which of the following would work?: ALL
24. Once the Redux Thunk middleware is enabled WE CAN....
25. Thunk middleware is the only way to implement asynchronous actions in Redux! F
26. Redux promise middleware is used to__ to dispatch Promises
27. To dispatch promise-based asynchronous actions, which of the following can be used? redux-pack
28. Redux-observable can be used to dispatch observable
29. Custom argument in thunk can be injected using with extra argument
30. Redux thunk is used to make- Asynchronous API calls
31. Only functions can be dispatched in asynchronous middleware. F
32. Middleware is basically__ High Order
33. Asynchronicity is all about "
34. occurrence of phenomena at the same time"
35. For more complex asynchronous actions, which of the following would work?: Saga

You might also like