How To Create An Application Using ReactJS And Redux

Introduction 

 
In this article, we will create a demo application using React, Redux, and web API. We will learn the basics of Redux and how to use Redux in a React application. Download the code from here.
 
Prerequisites
  • Basic knowledge of React, Redus, and Web API
  • Visual Studio
  • Visual Studio Code
  • SQL Server Management Studio
  • Node.js
  • Bootstrap
This article covers the following,
  • Create React Project
  • Basic of Redux
  • Environment setup for Redux
  • Create a Web API Project
  • Install Bootstrap and Axios

Redux

 
Redux is a predictable state container for Javascript applications. We can use Redux with any Javascript framework or library.
 
According to the Redox official website:
 
Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time-traveling debugger. You can use Redux together with React, or with any other view library. It is tiny (2kB, including dependencies), but has a large ecosystem of addons available.
 
Create a ReactJS project
 
First, let's create a React application with the following command.
  1. npx create-react-app reduxapp    

Environment setup for Redux

 
Install Redux
 
Install redux using the following command.
  1. npm install redux react-redux   
Install Redux-Logger
 
Install Redux-Logger using the following command.
  1. npm install redux-logger    
Install redux-thunk
 
Install redux-thunk using the following command.
  1. npm install redux-thunk   
Install redux-devtools-extension  
 
Install redux-devtools-extension using the following command.
  1. npm install redux-devtools-extension   
Now Install the Axios library and bootstrap by using the following commands. Learn more about Axios.
  1. npm install --save axios    
  2. npm install bootstrap   
Now right click on the Src folder and add a new folder named 'redux', and inside this, create a new folder named 'user'.
 
Inside the user folder, create 6 files named:
  • userActions.js
  • userReducer.js
  • userTypes.js
  • index.js
  • rootReducer.js
  • store.js
File structure of Redux folder:
 
Now open userTypes.js file and add following code:
  1. export const GET_USERS_REQUEST = 'GET_USERS_REQUEST'  
  2. export const GET_USERS_SUCCESS = 'GET_USERS_SUCCESS'  
  3. export const GET_USERS_FAILURE = 'GET_USERS_FAILURE'  
 Now open userActions.js file and add the following code:
  1. import axios from 'axios'  
  2. import {  
  3.   GET_USERS_REQUEST,  
  4.   GET_USERS_SUCCESS,  
  5.   GET_USERS_FAILURE  
  6. } from './userTypes'  
  7.   
  8. export const GethUsers = () => {  
  9.   return (dispatch) => {  
  10.     dispatch(getUsersRequest())  
  11.     axios  
  12.       .get('https://localhost:44317/Api/Student/Getdetaisl')  
  13.       .then(response => {  
  14.         const users = response.data  
  15.         console.log(response.data);  
  16.         dispatch(getUsersSuccess(users))  
  17.       })  
  18.       .catch(error => {  
  19.         dispatch(getUsersFailure(error.message))  
  20.       })  
  21.   }  
  22. }  
  23.   
  24. export const getUsersRequest = () => {  
  25.   return {  
  26.     type: GET_USERS_REQUEST  
  27.   }  
  28. }  
  29.   
  30. export const getUsersSuccess = users => {  
  31.   return {  
  32.     type: GET_USERS_SUCCESS,  
  33.     payload: users  
  34.   }  
  35. }  
  36.   
  37. export const getUsersFailure = error => {  
  38.   return {  
  39.     type: GET_USERS_FAILURE,  
  40.     payload: error  
  41.   }  
  42. }  
 Now open userReducer.js file and add the following code:
  1. import {  
  2.   GET_USERS_REQUEST,  
  3.   GET_USERS_SUCCESS,  
  4.   GET_USERS_FAILURE  
  5. } from './userTypes'  
  6.   
  7. const initialState = {  
  8.   loading: false,  
  9.   users: [],  
  10.   error: ''  
  11. }  
  12.   
  13. const reducer = (state = initialState, action) => {  
  14.   switch (action.type) {  
  15.     case GET_USERS_REQUEST:  
  16.       return {  
  17.         ...state,  
  18.         loading: true  
  19.       }  
  20.     case GET_USERS_SUCCESS:  
  21.       return {  
  22.         loading: false,  
  23.         users: action.payload,  
  24.         error: ''  
  25.       }  
  26.     case GET_USERS_FAILURE:  
  27.       return {  
  28.         loading: false,  
  29.         users: [],  
  30.         error: action.payload  
  31.       }  
  32.     defaultreturn state  
  33.   }  
  34. }  
  35.   
  36. export default reducer  
Now open store.js file and add the following code:
  1. import { createStore, applyMiddleware } from 'redux'  
  2. import { composeWithDevTools } from 'redux-devtools-extension'  
  3. import logger from 'redux-logger'  
  4. import thunk from 'redux-thunk'  
  5.   
  6. import rootReducer from './rootReducer'  
  7.   
  8. const store = createStore(  
  9.   rootReducer,  
  10.   composeWithDevTools(applyMiddleware(logger, thunk))  
  11. )  
  12.   
  13. export default store  
Now open rootReducer.js file and add the following code:
  1. import { combineReducers } from 'redux'  
  2. import userReducer from './userReducer'  
  3.   
  4. const rootReducer = combineReducers({  
  5.   user: userReducer  
  6. })  
  7.   
  8. export default rootReducer  
Now create a component named Users and add the following code:
  1. import React, { useEffect } from 'react'  
  2. import { connect } from 'react-redux'  
  3. import { GethUsers } from './redux/user/userActions'  
  4. function Users ({ userData, GethUsers }) {  
  5.   useEffect(() => {  
  6.     GethUsers()  
  7.   }, [])  
  8.   return userData.loading ? (  
  9.     <h2>Loading</h2>  
  10.   ) : userData.error ? (  
  11.     <h2>{userData.error}</h2>  
  12.   ) : (  
  13.     <div>  
  14.      <div class="row">    
  15.     <div class="col-sm-12 btn btn-info">    
  16.      How to Build an Application Using Reactjs and Redux    
  17.     </div>    
  18.   </div>   
  19.       <div>  
  20.         {userData &&  
  21.           userData.users &&  
  22.           userData.users.map(user => <p>{user.Email}</p>)}  
  23.       </div>  
  24.       <table class="table" >    
  25.                 <thead class="thead-dark">    
  26.                     <tr>    
  27.                         <th scope="col">Name</th>    
  28.                         <th scope="col">Age</th>    
  29.                         <th scope="col">Address</th>    
  30.                         <th scope="col">City</th>    
  31.                         <th scope="col">Salary</th>    
  32.                         <th scope="col">Department</th>    
  33.                     </tr>    
  34.                 </thead>    
  35.                 <tbody>    
  36.                     { userData.users.map(item => {    
  37.                         return <tr key={item.Id}>    
  38.                             <td>{item.Name}</td>    
  39.                             <td>{item.Age}</td>    
  40.                             <td>{item.Address}</td>    
  41.                             <td>{item.City}</td>    
  42.                             <td>{item.Salary}</td>    
  43.                             <td>{item.Department}</td>    
  44.                         </tr>    
  45.                     })}    
  46.                 </tbody>    
  47.             </table>    
  48.     </div>  
  49.   )  
  50. }  
  51.   
  52. const mapStateToProps = state => {  
  53.   return {  
  54.     userData: state.user  
  55.   }  
  56. }  
  57.   
  58. const mapDispatchToProps = dispatch => {  
  59.   return {  
  60.     GethUsers: () => dispatch(GethUsers())  
  61.   }  
  62. }  
  63.   
  64. export default connect(  
  65.   mapStateToProps,  
  66.   mapDispatchToProps  
  67. )(Users)  

Create a Web API Project

 
Open Visual Studio and click on create a new project:
 
 
Now select the project and click on the Next button.
 
 
Now select the project name and project location and click on the Create button.
 
 
 Choose the template as Web API.
 
 
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
 
Select EF Designer from the database and click the "Next" button.
 
 
Add the connection properties, select the database name on the next page, and click OK.
 
C
heck the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button.
 
 
Right-click on the Controllers folder and add a new controller. Name it "Users controller" and add the following namespace in the Users controller.
  1. using Reduxdemo.Models;  
Now create a method to fetch data from the database. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using Reduxdemo.Models;  
  8.   
  9. namespace Reduxdemo.Controllers  
  10. {  
  11.     [RoutePrefix("Api/Users")]  
  12.     public class UsersController : ApiController  
  13.     {  
  14.         RestaurantsEntities DB = new RestaurantsEntities();  
  15.         [Route("Getuser")]  
  16.         [HttpGet]  
  17.         public object Getuser()  
  18.         {  
  19.             return DB.Userdetails.ToList();  
  20.         }  
  21.     }  
  22. }  
Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");      
  2. config.EnableCors(cors);  
Now, run the application using the 'npm start' command and check the result.
 

Summary

 
In this article, we learned how to create a react-redux application. You can download the code from Github.