Introduction to React-Redux
Hi, I took this course on Front-End Web Development with React by The Hong Kong University of Science and Technology, so this is a gist of that course.
This Blog is pretty Theoretical, So kindly refer for more information links along with documentation of Redux.
Prerequisites would be HTML, CSS , Bootstrap and basic JS
- http://programmerprodigy.code.blog/2020/06/18/web-developmenthtmlcss-basics/
- http://programmerprodigy.code.blog/2020/06/24/javascript-basics-for-web-development/
- https://programmerprodigy.code.blog/2020/08/15/front-end-web-development-with-react/

Very often, you see yourself repeatedly solving similar problems. If we have a well-specified documentation of how to solve these problems, why keep reinventing the wheel every single time? So that is where the software engineering’s design pattern concept originates. Sometimes, you also see people referring to this as an architecture pattern.
In the MVC framework, the model manages the behavior and data of the application domain. And the model responds to requests for information about its current state. So, typically when the view wants to render, or the view wants to update itself, it might query the model in order to obtain information, so that it can be rendered appropriately to the user. The model also will respond the requests for change of its state. This is usually done through the Controller. In an event-driven system, the model also can be configured to notify observers. So, viewers can register themselves as observers for the model and so when the model is updated, the views will be automatically triggered to update themselves based on the change to the model state.
The view itself, is concerned with presenting the information to the users in a user interface element. In such a way that it facilitates both the presentation of information to the user and also enables the user to interact with the application. So, the view may represent one representation of the model state.
Q.What is the controller in the MVC framework?
The job of the controller is to receive information from that view. So any user interaction that is formed will be captured and then passed on to the controller in order to act on these user interactions. And it is the job of the controller then to initiate a change of the state of the model if it is required in this particular situation. So, the controller will appropriately cost the change of the state of the model
The Model View View-Model approach is in some sense, a derivative of the Model-View-Controller approach. You have the model that represents the business logic and the data for your application. From the model, you derive a View-Model, which encapsulates that part of the information that is required for rendering a specific view. So the View-Model is the abstraction of the view, that exposes the public properties and the various comments that are available. So this provides a declarative data binding.
The simple React approach that we have taken with one root component that is holding the entire state of the application will not scale in that situation. So it is better to move that skate off your application into its own separate unit in some way. And this is where the model view controller approaches it that we just talked about might come to our help. Because in the MVC approach we see that the model has captured the entire state of your application and any changes that you want to make to the model from the view will have to go through the controller to the model. And then changes to the model may result in the views or some parts of the views being re-rendered. Now, the MVC of course is a wonderful approach and has been very effectively used for many web applications.

Q.Does MVC work for React?
Now when React started out, React was touted as the V in the MVC. And that was the way it was being approached earlier. It has gone beyond being a simple rendering of the view and you see a complete React application being developed.
But if you do so, you can easily have a fully functional React application. But that doesn’t scale very well. And this is where you want to move to a full fledged MVC approach, where you capture the entire state of your application, move it into a model, and then let that dictate how the views are being rendered.
Now, the MVC approach when used by Facebook, they encountered certain issues with the MVC approach. Now, there is a very well presented discussion in a talk given by Facebook on why they faced issues with using the MVC architecture in some of their applications. With the issues like cascading updates where change in one model may result in that causing a change in another model and which causing a change in another part of the model and so on. And this cascading updates of the model state pretty soon becomes very difficult to handle. And so they found that this approach of the MVC approach doesn’t work very well with their kind of applications, especially things that they developed with React. And that is where they came up with their own approach called the Flux architecture.
Q.What exactly is The Flux Architecture?
It is a suggestion idea or a pattern for you to organize your code, and not necessarily the only way of doing things. But, they found that the Flux approach works very well for applications like what you developed with React.
Now, what is the salient feature of this Flux architecture or the Flux approach for developing applications? In this, one of the salient features is unidirectional data flow. The problems that they encountered with MVC was the fact that the updates, as we see lead to a cascading flow of updates within the models, and becomes a tangled web, which becomes untenable after a period of time. And so this is where they decided that all updates have a unidirectional flow. So here the central unit for your architecture is the store. In the Flux architecture you could have multiple stores,

Introduction to Redux
Redux derives a lot of its ideas also from the Flux architecture but it is a realization of the Flux architecture. Now, let’s talk about Redux, and how we can make use of it with a react application. Now, Redux was proposed by Dan Abramov. In one of his talks, in Riyadh, Europe, a project where he was trying to demonstrate ideas about time-travel debugging, and so on, and so he created this framework to demonstrate his idea, and then it ended up being very popular, as a Flux-like approach for a react application. Inspired by all these, Redux was suggested as an approach for structuring your react application.
Redux is a general approach that supports a way of managing store, unidirectional flow that is characteristic of the Flux architecture and much more.
Redux, the reason for adopting something like Redux is that it makes state mutations predictable. Also, Redux supports things like time-travel debugging, we will see that there is a consistent way and you can even observe how your state is being changed and there is a consistent way that you modify the state and so on. Because when you adopt the Redux architecture for your react application, it becomes even more easier to handle the states.
The three main principles of Redux as stated by Dan Abramov,
- The first principle that he states is that in Redux there is a single source of truth or there is a single state object tree within a single store. The Flux architecture allows you to have multiple stores that need to be coordinated together by the dispatcher, and when it dispatches the actions to the stores, all these stores need to update themselves. In Redux, there is a single store. The single store has a single state object tree within the single store, and so that becomes the single source of truth for your applications, be it react or angular, wherever you apply Redux
- Second, the state is read only. Meaning that you can only do gets on the states. So, only getter operation source supporter of state by the store. Any changes to the store should be done only through actions. Again, this comes back from the Flux approach that we have seen. The uni-directional data flow approach that we have just seen in the previous lecture.
- The third part is that any changes that you make to the state are made by only pure functions, what in Redux terms are called as reducer functions. Now, what does this pure function do? The pure function takes the previous state of your application, and the action that is specified, and given the previous state and the actual that is specified, it’ll generate the new state for the application. When the next state or the new state is returned, this new state will not be a modification of the previous step. Previous state will remain as such. But the pure function will return in new state, which is derived from the previous state, but then it’ll create a new state in return. So, there is no mutation of the previous state. Now, within your store, you will store this next step. So your next state of your application will mutate to the next state. Again, because of the use of the pure functions, the immutability of the state is preserved.

For more information,
https://redux.js.org/introduction/three-principles/
The Redux Approach
The Redux approach which uses a single store and a single state tree makes it easy for us to implement a few things. Logging of changes to the state is very easy. Now, as you saw because we use pure functions, the next state is always generated from the previous state, but the next state does not change the previous state directly. The pure function returns the next state. So, you can track all the states of your application as they change, and you can log the changes.
So for example, if you encounter a bug, you can walk backwards and then check through the state changes to see how you arrived at the current state and if there was something that was wrong in the way the state was changed. So that allows you to do undo operations so if you don’t want to process the change that you’ve done, it is very easy to support undo. It comes naturally in react as we will see there. State persistence comes in, and then also time-travel debugging also comes to your aid.
Now, here in Redux, the dispatch also is considered part of the store. So, your action is dispatched into your store. The store then uses the dispatch of the previous state and then sends this as input to the Reducer functions**. The Reducer function will return the state from these two inputs, and the next state is then stored in your store. And so, that is how your store gets updated. The views themselves are watching the store and any changes to the state will result in the emission of the change to the view and when the view notices the change, the view will go and get the state. And then, if you may generate an action in response to the user’s interaction with the user interface component and so on.** So now, let’s examine a few of the Redux concepts now.
The state in Redux is stored as a plain JavaScript objects, JavaScript object tree that we store there. And in action is also a plain JavaScript object with a type field. The type field specifies what kind of action that is and also it carries some payload. That’s the term that they use, payload. The payload specifies what changes need to be initiated.
The reducer as you see is a pure function that takes the current state and action and generate the next stage of your application. Now, the update to the data is done immutably, if you have an object you won’t change that directly, but instead you derive a new object by copying the previous object and then generate a new object as a copy with the modification applied. You generate a whole new object from the previous object. That is what the preserving the immutability of the objects means.

Q.What exactly is the Redux store?
The store becomes the storehouse for your application state, and any business logic that modifies the application state. So the store encompasses this whole thing, and the only way you can modify your application state within the store is by requesting the store. You don’t have any setters that the store make available to you.
The Redux store contains the state and the reducer functions and the dispatch. So, the Redux store itself holds the current state values. So, that is where it has been kept as a pure JavaScript object. And this Redux store is created in your code using this createStore() method. So, that’s how you end up initializing Redux store. This Redux store also supplies three methods.
- The dispatch method is where you will supply the action object and then specify what changes you want to make to the state.
- The getState method, to get the updated state from your store.
- Callback function that will be run every time an action is dispatched. So, the dispatching of an action will result in an update to the state. And then, that you can subscribe to the changes and then watch the changes. And you can use getState to get the updated state from your store.
When the store updates its state, the store will emit a change which the controller views will watch for. Whenever a change is emitted, then the controller views will go back and be able to get the updated state. And this, in turn, may result in re-rendering of parts of your views or parts of your components within your React application. So that is how the data flows. But again, it is a unidirectional data flow. Now the views cannot directly change the store. If a view needs to change anything in the store, then, this is the approach that they expect you to take.
So any change that you want to make in your store because of user’s interaction with any particular view within your application, will have to be reflected back to the dispatcher in the form of an action. Now the actions themselves support what I call action creators.So new actions that are initiated will propagate through the system in response to the user interactions. And this will be delivered to the dispatcher, and the dispatcher becomes the center unit that controls all the changes and mediates to ensure that changes to the store are sent through it. There is no other way for you to change the state of your application. So this approach where there is a unidirectional data flow, any changes have to go through the dispatcher, and then be sent to the store. And changes to the store will reflect into your controller views are by the store emitting the change and then the controller view’s then pulling in their changed state through getter operations on the store.

For more information,
https://redux.js.org/api/store/
Q. How to use the react-Redux package for binding your react to your Redux application ?
So, you will take your react component, what we call as the component that previously was holding the state. When you move the state into the Redux store, you want your react component to be able to obtain the copy of the state. So, within our example application we’ll take our main component and tie it to the Redux store through the connect method that is made available react-Redux package. So, this will enable you to connect your component to the Redux store. What does connect provide for you? The connect provides a wrapper container component. Remember we talked about container components in the previous module. So, when you use connect, the connect automatically generates container component around the component within which you apply this. And then, that allows you to connect to the Redux store. And then the state can be obtained from the Redux store within your application.
Yarn commands to add redux and react-redux to your react application,
yarn add redux
yarn add react-redux
How do I connect my react component to the Redux store? How do we synchronize the state changes? How do we obtain any state modifications to automatically update the state in our react application and thereby, result in rendering of our views and so on. Then you apply that connect function to your react component. The connect function also takes two optional arguments called mapStateToProps and mapDispatchToProps.
- The mapStateToProps is called every time store state changes. So, as you recall, the Redux store, whenever it detects a state change that will emit the change, and then that will result in your component need to go back and pull in the state from the Redux store. Now, because you are connecting your react component to the Redux store, so to this connect, when you supply this mapStateToProps, the state here means the Redux state. So, that state will be mapped into the props of your component. And so, the state information becomes available to props in your react component, and those props can then be parsed down to your children as required in your application. Now similarly, previously we’ve been implementing all state changes by implementing functions within the main component which will be called by your child components.
- Now, changes to the state will have to be dispatched to the Redux store. Now, this is facilitated through this mapDispatchToProps.
const mapStateToProps = state => {
return {
dishes: state.dishes,
comments: state.comments,
promotions: state.promotions,
leaders: state.leaders
};
};
const mapDispatchToProps = (dispatch) => ({
fetchDishes: () => { dispatch(fetchDishes()) },
fetchPromos: () => { dispatch(fetchPromos()) },
fetchComments: () => { dispatch(fetchComments()) },
fetchLeaders: () => { dispatch(fetchLeaders()) },
});
We need to set up the reducer function because our store needs to know what to do when an action is dispatched to it.
React Store becomes available to all the components within my React application. So, that’s the change that I need to make to the app.js file. Now, the last step is to make use of the Connect from react-redux to connect my React application to the Redux Store.
For more information,
- React and Redux
- Redux Basics Documentation
- The Flux Architecture
- Redux Tutorials
- Flux Architecture In Depth Overview
React Redux form
Now, with the introduction of redux into our react application, we can take advantage of the availability of the redux store in order to process the information within our form into the redux store. Now this is where the new package called react-redux-form comes to our aid. It provides you with a lot of features that enable you to leverage redux for your form persistence and also form validation.
This is a versatile, fast and intuitive library for creating complex and performant forms in React using Redux. Now, the React-Redux-Form itself persist the state of your form into a model in the redux store. And React-Redux-Form also provides a collection of reducer creators and action creators for us that enables us to do all this work for us without writing much coat. Now that’s where the React-Redux-Form takes care of all the grunt work behind persisting the form in the Redux store.
Say, for example, you are on a view and you’re filling out a form and then you navigate out of the view. Now very often when you have standard react components, when you move out of a view, the state of the, whatever local state that you stored in that component will get destroyed. And so when you return to the same view, if you had filled up a form, the form would remain unfilled and deployed. Suppose you want to persist the state of the form even across page reloads or as you navigate in and out of a view, then React-Redux-Form would be of use to you. So, this is achieved by the form data being stored in the redux in a model. And all the details of how this persistence is done is automatically taken care of by React-Redux-Form without us needing to do any reducer functions or the action creators on our behalf. And also, React-Redux-Form brings in its own support for validation
<Row className="form-group">
{/*The simple f-o-r, for, will be confused with JavaScript's for, so that's why we'll have to use label htmlFor here. */}
<Label htmlFor="firstname" md={2}>First Name</Label>
<Col md={10}>
<Control.text model=".firstname" id="firstname" name="firstname"
placeholder="First Name"
className="form-control"
// Validadting all the condtions at line 9
validators={{
required, minLength: minLength(3), maxLength: maxLength(15)
}}
/>
{/* For all the errors due to a particular validation */}
<Errors
className="text-danger"
model=".firstname"
show="touched"
messages={{
required: 'Required',
minLength: 'Must be greater than 2 characters',
maxLength: 'Must be 15 characters or less'
}}
/>
</Col>
</Row>
<Row className="form-group">
<Label htmlFor="lastname" md={2}>Last Name</Label>
<Col md={10}>
<Control.text model=".lastname" id="lastname" name="lastname"
placeholder="Last Name"
className="form-control"
validators={{
required, minLength: minLength(3), maxLength: maxLength(15)
}}
/>
<Errors
className="text-danger"
model=".lastname"
show="touched"
messages={{
required: 'Required',
minLength: 'Must be greater than 2 characters',
maxLength: 'Must be 15 characters or less'
}}
/>
</Col>
</Row>

For more information,
- React Redux Form Documentation
- The boring React Redux forms
- How to populate react-redux-form with dynamic default values
- Should you store your form state in Redux?
Redux Actions
So, what exactly are Redux actions? Redux actions are payloads of information that are sent from your application to the store in order to effect any change in the store’s ticket. Now, when you send an action to the store, you use the store’s dispatch method to send the action to the store.
Now, when that action is constructed, what exactly does the action contain? The action is a plain JavaScript object. Now, when you define the structure of this JavaScript object, this JavaScript object should contain a type field or a type of property, which indicates what type of action this is. So when this action is delivered to a Reducer function, the Reducer function will be able to interpret what type of action that is, and then initiate the appropriate action to change the state of our store there.
So, the type field is essential or the type property is essential in the JavaScript object. The rest of the JavaScript object can contain anything that is meaningful to your application, any data that is required for the action to be created. Now, this is what we will refer to as the payload which comes as part of your action.
To help us generate various actions, we make use of action creators. The action creators are nothing but functions that will return the action JavaScript object. So this function encapsulates the process of creating this action JavaScript object. Now, the resulting action object can then be passed to your store through the dispatch action. So, you will use the action creator to create an action object and then dispatch it to your store using the store dispatch method. Within your store, you have Reducers that take in the action as one of the parameters, and then takes in the previous state or the current state of your application as the other parameter and that generates the used state. So the Reducer should take the previous state of action and return the next state. Now, when it generates the next state, one thing that we have emphasized earlier also and I’ll emphasize again, is that we should never mutate the current state. So, when you need to return the next to state, you will make a copy of the state, and then make modifications to this copy, and then return that copy from the Reducer function there.
So, you’ll see that your Reducer function receives the previous state and the action. Now, when the action is received, the action has to be then examined and then based on the type, a property in the action. So now you’ll see the reason for the type property in action. Based on the type property of the action, you will write typically that the Reducer function as a switch statement. So you will use the action type as the switch. And then switch on the action type, and then decide what needs to be done within your Reducer function. Now, the default case is that, if your Reducer is not going to act on that action supplied, sometimes the user may not have to make any changes to the part of the state that it controls in response to an action being delivered to it. In that case, it would simply return the previous state.
So, every action object should contain a type. So, how do we define the type? This is where we will use the action types and then add comment here. So, now you see the reason for defining the action types in a separate file and then importing it in here and then you can easily define the type to Redux. All the types of actions are all captured in the action types there and then you can import it
For a simple application, a single Reducer function may be more than sufficient, but when you have complex applications especially when the state of your application has many parts, then it is more easier to split your Reducer into multiple functions. So depending on the shape of the state, you can split the Reducer into multiple functions and then each such function will be dealing with one part of the state. And then after that, you can recombine them to form the overall Reducer function.
To combine them together, Redux provides us with a method called as combineReducers. So, we will import the combineReducers in here, and then when we create the store here. Instead of just doing Reducer initialState, we will say, combineReducers. And inside this combineReducers, we will specify how exactly to combine the various Reducers that we have defined here. The four simpler Reducers that we have defined here. So, to compose the overall global state, we have to map these Reducers into each one of the four properties there.
Now, I will follow a standard pattern and then define the second part as the payload. The payload contains whatever needs to be carried in so the data that is sent back by the addComment. This is just my way of defining it, and if it is a very natural way of specifying whatever data needs to be carried in the action object to the reducer function here.

So, when you submit the comment, you’ll see that the submission of the comment will trigger action to be sent to your redux store, and then this action will result in the comment being added into the comments part of the state of your redux store, and then when the changes, then that will result in the store emitting a change, and that will result in your main component going and getting the updated state from the redux store, and then the main component passes the new state to all the chilled components, and then when you come down the RenderComments component realizes that the comments part has changed, so it will have to be rendered. So, react takes care of re rendering that with new the comment added into the list there. So, now you see how an action can trigger a change in the redux store and that immediately gets reflected back into our react applications view there.
For more information
Redux Thunk
Now sometimes when you dispatch a Redux action, you may want to intercept it on its way to the tool and make some modifications to the action before letting it pass through on to the store. Now this is where the Redux Middleware and Redux Thunk come to our help.
So what exactly is thunk? So thunk is in programming. What we mean by thunk is a subroutine that is used to inject an additional calculation into another subroutine. So this is a way to delay a calculation and its result is needed and also allows you to insert operations at the beginning or the end of another subroutine.
So before that point, you can intercept action and effect some changes before the action reaches the reducer. So this is a place which enables third party extensions to be injected into your Redux application. So for example, if you want to log all the actions that have been dispatched, that is a good point for you to first capture the action, log what the action is and then let it move on to the reducer, and then you can then log the state of the application after the action is effected.
Similarly, if you want to allow asynchronous API calls, so for example, you dispatch an action but the action would initially require access to a server from radio fetch the data and then send the data into your Redux store. Then that is also a good place to interject a middleware in order to intercept the action and then carry out basing API call and then let the action proceed forward into the store.
So the middleware can be typically used for inspecting the action and then also the state. You can even modify the action, you can dispatch all that actions and then wait for the results from those actions before you allow this particular action to take place, you could even stop an action from reaching the reducers if it is something that you wish to do, and so on
So there are many applications for a middleware that allow you to achieve your end goal. Then you need to use the middleware in your Redux application then you use that applied middleware function that is available from Redux, and so this will enable you to set up the middleware pipeline, and then this returns a store enhancer. So when you call ”Apply middleware,” it will return a store enhancer which you can then pass in as a parameter to the create store function that we have already seen being used when we created the store.
So the inner function that you define inside a thunk gets access to both the dispatch as well as get state store. What does this permit you to do? Because you have access to get state, you can examine the state and then see if this action fits and can be allowed with the current state. So that would allow you to even modify the action, and also you’ll get access to dispatch. So for example, you can stop the current action, do something else, come back and then dispatch the action into the reducers.
The logger middleware that we have put into our application. How does the logger middleware work? Now to see the logger middleware’s operation in your browser, open your JavaScript console of your browser. So in the console, what does the logger do? The logger prints out all the various actions that are dispatched and also as you can see, it shows the previous state, the action and the next state.

Now, if we want to make use of the full power of the React-Redux-Form whereby the form state is persisted in the Redux store instead of in the components state, then we need to update our form to make use of the regular form rather than the local form from the React-Redux-Form. The React-Redux-Form brings in its own set of support for all these on our behalf, so we don’t need to write our own reducers or our action creators and so on, React-Redux-Form fills in all the details by itself.
For more information,
Setting up a Server using json-server
It helps us to quickly set up a simple server with several data that is given to it in the form of a JSON file. And also sum up images that might be required by our application.
To install json-server,
npm install json-server -g
To start json-server,
json-server --watch db.json -p 3001 -d 2000
For more information,

Promises:
As we realized when we make any request to a backend server, it is going to take some time for the results to become available. If we do such a request while we are proceeding with our work, then, there is a high likelihood that our computation will get stuck at the point waiting from the results. This is a no no in terms of a good user experience. So, it is important that whenever your results are going to take time you should be able to proceed forward without waiting for the result. Promises provide us with a way of dealing with this.
Q.what exactly is a promise?
A promise is a mechanism that supports asynchronous computation.
Now, in using a promise, the promise provides a mechanism or a proxy for a value that is not available at the moment that you asked for it. So a promise will return a promise to you saying that when the result becomes available it’ll come back and deliver the results to you. So, a promise returns a proxy object to you and you hold onto the proxy object and that proxy object will give you access to the results when they become available. There is a method in how you wait for the results. You actually don’t suspend your computation at that point instead, you configure a way of accepting the results when it comes back from the promise. To put it in a nutshell, promise represents a value that would be available at a future time. It may be also immediately available in which case the promise will return the value immediately. But in case it needs to return a value at a future date then it gives you the promise that that value when it becomes available, will be returned to you.
There’s always the possibility that the promise cannot be met because the results are unavailable for whatever reason. In that case, an error will be delivered to you, or a reject will be delivered to you and it is up to you to deal with the fact that the promise was rejected.
So when you deliver a promise to somebody the promise internally will have a function that will deal with both the resolve and the reject options inside there. Then you write code.
import * as ActionTypes from './ActionTypes';
export const Comments = (state = { errMess: null, comments:[]}, action) => {
switch (action.type) {
case ActionTypes.ADD_COMMENTS:
return {...state, errMess: null, comments: action.payload};
case ActionTypes.COMMENTS_FAILED:
return {...state, errMess: action.payload};
case ActionTypes.ADD_COMMENT:
var comment = action.payload;
return { ...state, comments: state.comments.concat(comment)};
default:
return state;
}
};
So, you can chain a set of then methods together to deal with promises one behind other. If the result is immediately available or if you are going to reject immediately then promise provides a method of immediately returning without waiting for their promise to either resolve or reject. In that case, you would simply say promise with the capital P.resolve and promise.reject, and then return either the result or the error immediately.
[Image no longer available]
Fetch
The Fetch API is proposed as a modern replacement for XMLHttpRequest. Now, it is quite new and so some of the older or legacy browsers do not support it yet. But the newer browsers are all beginning to support the Fetch API as part of the browser itself. Now this provides an interface for fetching resources including from across the network. That’s indeed the purpose of Fetch. And Fetch provides a more powerful feature set and more flexible feature set than what XMLHttpRequest provides.
Now Fetch API inherently supports promised based approach for communication. So Fetch supports promises inherently and that is what makes it valuable for use in communicating with a server
In Fetch, a request represents a resource request. And similarly, a response represents the response to the request that you send to the server. Now the request and response are objects that you have access to and can manipulate it. Similarly, the headers object represents the request/response headers. Now you can query the headers, extract information, you can add headers to an outgoing request. You can extract headers from the incoming response and make use of them within your JavaScript code.
In addition, the body itself is another object that is part of the Fetch API and it provides methods relating to the body of the response or the request message. Now, you can declare the content type of the body, how the body should be handled. You can even put information into the body. You can extract the information of the body and so on, and that is all supported through Fetch API.
Q.how do we make use of the Fetch API?
A simple usage of the Fetch API is within your JavaScript code, you’ll simply say fetch and then supply the URL of the server that you want to access. So in this case representing the URL as a baseURL +, an extra part of the URL. This is exactly what I will use in the code in the exerciser slot. The baseURL is configured with the HTTP://, URL address for the server, and then the extension is the specific resource on the server that we are accessing.

Now once you issue this will return a promise object. Now when it returns a promise object, then on the promise object you can apply it then to the promise object. So as you can see you apply the then, and within the then you’ll get access to the response object. Now once you get the access to the response object, this response object is a raw body in the response message. You can convert it if you know that the response body contains data in JSON format. You can simply can work that by saying response.json and then that will give you the body in JSON format and so it is more easy for you to process that within your JavaScript code.
If you want to perform any other kind of HTTP request, other than get, then you can explicitly specify the method in a second parameter that you will supply to the fetch. The second parameter will be a JavaScript object with properties where you specify the details of what goes into the message. So, for example, if you are posting some data to a REST API endpoint, in order to create a new object on the server side. Then you could simply say, fetch and then supply the REST API end point following that within a JavaScript object you can specify the method as POST for example.
export const fetchDishes = () => (dispatch) => {
dispatch(dishesLoading(true));
return fetch(baseUrl + 'dishes')
.then(response => {
if (response.ok) {
return response;
} else {
var error = new Error('Error ' + response.status + ': ' + response.statusText);
error.response = response;
throw error;
}
},
error => {
var errorMessage = new Error(error.errorMessage);
throw errorMessage;
}
)
.then(response => response.json())
.then(dishes => dispatch(addDishes(dishes)))
.catch(error => dispatch(dishesFailed(error.message)))
}
Now, when you send the POST request the server will then respond with a response message. And that response message can then get processed appropriately by using then and then catch, as we see. When the data is posted to the server side, the server will respond back with a reply. The reply might actually contain a copy of the data that is posted. Now this depends upon how you arrange your server side and what the server will send back in response to a post request. Now, if you’re implementing the server you have the full flexibility of implementing what the server will return in response to a post request.
What fetch does is if the status code in the response message is within the normal limits 200 to 299 then it will set a property call as OK on the response. And so you can check this response, start OK to see if it is true or false. If it is true, then the response that you get is a valid response. And so you can simply return that response over to the next then that you chain into the sequence of then there. Otherwise, so this is the otherwise part, if it is not then you recognize that your status code is outside the normal range that you would consider a normal response from the server side, in that case we will handle it with the else part. Here you have to explicitly create an error like this here, so you are extracting from the response. You’re saying response.status, response.status contains the status code.
Now if the server explicitly or if in communicating with the server you experience an error. So which means that you never even managed to communicate with the server. In that case, fetch will generate an error response and that is handled by giving a second callback function to the then. Promises allow you to give two callback functions as parameters to the then. The first callback function will be used when the promise resolves correctly. The second callback function will be used when the promise is rejected. So the error part is where the rejection of the promise is handled. So if it is rejected, then you will create an error message from the error message and then throw an error at that point. That’s another way of handling errors that are caused. So this is fully your responsibility, this part of the code is something that you implement when you use fetch.
For more information,
- JavaScript Promise
- JS Promise (Part 1 – Basics)
- JavaScript Promises for Dummies
- JavaScript Promises: an Introduction
- Introduction to fetch()
- Using Fetch
- Fetch vs. Axios.js for making http requests
React Animations
Animations in the user interface adds a lot to the user experience for your application. Subtle animations that give visual feedback to the users, definitely add to a better user experience
Now, the React-transition-group supports React animations through a set of CSS transitions that we can express using CSS classes. Now, the React-transition-group used to be part of React in some of the very old versions of React, but there after has been separated out into its own NPM module called as React-transition-group. So, now if you want to use it in your React application unit, explicitly install that and then make use of it in your application.
The React-transition-group provides a set of components that enable you to manage components tips including mounting and unmounting. So, they help to recognize when components are getting mounted and unmounted, and then they are designed specifically with animation in mind. The components supported by the React-transition-group include a transition, a CSS transition, and a TransitionGroup, each meant for a specific purpose. The transition is a generic transition and it lets you describe a transition from one component state to another component state over time. Now, when you define component state, the transition component has four states that it goes through: the entering, the entered, the exiting and exited state. So, whatever you put inside the transition component, you will apply the corresponding transitions when the enclosing children are being rendered, or mounted, and then unmounted.
The CSS transition has a property by name class names, and the class names takes a value there. So, for example, in this example, we give a class names as page. What this means is that, it will take four CSS classes which you will define in your CSS5. The four classes would be page enter, page interactive, page exit, and page exit active. Now, the page enter will be applied when you go into the entering state, and then when you reach the entered state, the page interactive will be applied, and the page exit and exit active as you would expect. These CSS classes have to be specified, and within those CSS classes, you’ll specify what kind of transition you want to cause. You can change the opacity, you can do the transformation, so x and y transformation on your elements and so on can be applied.
.page-enter {
opacity: 0.01;
transform: translateX(-100%)
}
.page-enter-active {
opacity: 1;
transform: translateX(0%);
transition: all 300ms ease-in
}
.page-exit {
opacity: 1;
transform: translateX(0%)
}
.page-exit-active {
opacity: 0.01;
transform: translateX(100%);
transition: all 300ms ease-out
}
The transition group is the component that the React-transition-group supports. The transition group manages a set of transitions that you apply to a list. So, if you are applying to a list, then you know that the list items may come in and go and so on. So, for example, if you have a long list and then you add a new item to the list and you wanted to animate the entering of the new item into that list, then the management of that, by using the transition class, that if you enclose the entire list in a transition group and then apply the transition to each list item, then the in property of the transition and the turning of the in prop to true and false will be controlled by the transition group. So, it automatically toggles the in prop for the components that are enclosed inside it. So, if you apply to a list each list item, the in prop will be toggled as required. So, if you add a new item into the list, let’s say, for example, your data changed and a new item just got added into the list, the new item will animate itself into the list in the view by using the TransitionGroup.

For more information,
- Animation Add-Ons
- react-transition-group
- React Transition Group Documents
- react-animation-components
- How to build animated microinteractions in React
- UI Animations with React — The Right Way
- React Animations in Depth
- What’s the most developer-friendly React animation library?
- Amazing React animation with react-pose
- Redux Actions
- Redux Reducers
- Redux Usage with React
- Cross-Fetch
- Animation Add-Ons
- react-transition-group
- React Transition Group Documents
- react-animation-components
Introduction to Webpack
What exactly is Webpack and how does it help us to build the distribution folder?
For our React Application, we had used Create React App to scaffold out our React Application. Create React App itself, uses React scripts and NPM module underneath for supporting all the various activities that we need to do for our React Application. It internally uses Webpack to do the building of the distribution folder.
Webpack, this is a definition from the Webpack documentation itself. It says, Webpack is a module bundler for modern JavaScript applications. Now, what Webpack does is, it looks at the entire structure of your application. So, it recursively traverses through your code looking to see how best to bundle the information into what is called as bundles. Then that pack looks at your code. It treats every file that you have, be it a JavaScript file, be it a CSS file, be it a Sass file, be it an image file, whatever, it treats every one of them as modules from its perspective and then it decides, what is the best way of packaging this modules into what are called bundles that can be downloaded from the server to your web browser in a comfortable and convenient manner.
hat pack knows how to package them and treat them as JavaScript modules when it prepares those bundles. So, a bundle is something that groups together modules that belong together. So, it bundles those modules together that should be served to the client in a single response to a request. So that pack itself makes a decision on saying, what part should be joined together into a bundle and should be delivered together so that the rendering of your web application is done in the most effective manner?
So, what Webpack does is, it starts at the top most level. So, it’s starts there and then it follows all the imports that you use in those down their path and build up a hierarchical organization of all the different parts. So, what is called as a dependency graph is built by the pack. Now, using this dependency graph, that pack then decides how to package its bundles and that emits one or more bundles as they make sense for your particular application that Webpack is bundling. In the process of doing it, when it is handling non-JavaScript files, like CSS, HTML and Sass or images and so on, then it uses plugins that enable you to pre-process and minify those files, those non-JavaScript files into a way that they can be bundled into your Webpack bundles. If you are using Webpack from the scratch, then you would describe some of the configuration for your Webpack to work on these files in a file named webpack.config.js which should be included in the root folder of your application. Now, when we talk about Webpack, there are four concepts that are important for us to understand on how Webpack works on things.
There are four concepts that are important for us to understand on how Webpack works on things.
- The first one is entry. Entry is a point that which the Webpack should start and follow down to build the dependency graph.
- The Second part is what we’ll call the output. In Webpack, the output is the set of bundles that are Webpack prepares on your behalf.
- The third one is loaders. Files that are not JavaScript, they have to be transformed and then put into your bundles by using appropriate transformations and then they will be added into your dependency graph. This is where the use of the various plugins come in.
- The plugins help you to perform the various actions and custom functionalities, like compilations that you need to do for building up your bundles. So, it will help you to transform your CSS into a way that you can package into your JavaScript bundles and so on.

For more information,
For GitHub repository, https://github.com/kakabisht/React_Course_assignments
For the previous blog on react blog, https://programmerprodigy.code.blog/2020/08/15/front-end-web-development-with-react/