Getting Started With React Redux : Part2

Manav Pandya  Print 
06 Oct 2018
 
Intermediate
358

In our previous part, we have seen many concepts like What is Redux, how to use redux, what are the different advantages of Redux with React, and most important thing is that Why we can use Redux with Redux. In this part, we are going to see one example about how to use Redux with React, but for that, I would recommend you to go through Getting Started With React Redux : Part1 before proceeding with this part.

We already learned some important concepts like Action, Store, and Reducer, so now let’s implement simple Read operation of CRUD, let me tell you that I am not going to cover complete CRUD operation. We will learn it later on using the separate article.

Implementing Redux with React

To implement Redux with React, we will follow a few steps o perform Read operation, in which we are going to fetch the list of Employee from our local json-server.

Step 1

The first and primary step is to create react app using below npm command.

Create-react-app crud-react-redux

After executing above npm command, our project will be created and we are going to create the following project structure.

As you can see into the above image, I have created separate folders like.

  • Components

    Used to store all the related components into the application.

  • Redux

    It consists of different child folders to store action, action types and reducers related to different modules.

Step 2. Install Dependencies

To work with Redux and other things, we need to have installed few dependencies, for that we need to just execute a few npm commands which are listed below.

Commands

Command
Description
Npm install react-redux
It is official redux binding to use different functions to use into your project
Npm install redux-thunk
Middleware for Redux which is used to call the actions creators which returns function
Npm install Redux
It is a state container which consists module bundler, and also includes pre-compiled production and development builds
Npm install axios
Used to call the API and it is just an HTTP based client for the browser
Npm install reactstrap
To use different bootstrap components like Table in our application
Npm install –g json-server
We are going to create fake API using JSON data
Npm install bootstrap
To use bootstrap minified CSS

Install all the above-listed dependencies, because we are going to work with all those packages into our application.

Step 3. Create fake API data

We have already installed json-server dependency; let me tell you that what json-server is. Json-server is used to create fake API for mockup, because sometimes we need to test some functionality without waiting for API to be created by the back-end developer, at that time json-server will be useful to generate fake data using few steps. For that, we will create JSON file which consists fake JSON data for our demo, create a new file named data.json.

/public/data.json
 
 {
 "employees": [
 {
 "firstName": "Manavv",
 "lastName": "Pandya",
 "email": "manav@gmail.com",
 "phone": "12345678910",
 "id": 1
 },
 {
 "firstName": "test",
 "lastName": "test",
 "email": "a@b.com",
 "phone": "12345678910",
 "id": 2
 },
 {
 "firstName": "test1",
 "lastName": "test1",
 "email": "a123@b.com",
 "phone": "12345678910",
 "id": 3
 },
 {
 "firstName": "test2",
 "lastName": "test2",
 "email": "a1234@b.com",
 "phone": "12345678910",
 "id": 4
 },
 {
 "firstName": "test3",
 "lastName": "test3",
 "email": "a12345@b.com",
 "phone": "12345678910",
 "id": 5
 }
 ]
 }

In this data.json file, I have created a total 5 different records for the employee, so we will render it inside a table using redux pattern.I know you are eager to know that how we can call these records, so for that we need to use one command as described below.Go to the directory inside we have created a data.json file and execute below command.

  • Cd public

    And then write a single line of command to run json-server.

  • Json-server data.json

    When you execute the above command, you can see the output in the console like this.

Open above URL in the browser and see the data of employee and you will have an output like this.

Now we have the API which has 5 records of an employee, let’s implement redux part to get the list of the employee.

Step 4.

In this step, we are going to create a few important files regarding redux like action, action types, and reducer. Create a new folder inside src directory named redux and create child folders like.

  • Actions

  • Action types

  • reducers

/src/redux/actions/actions.js
 import { GET_EMPLOYEES, ADD_EMPLOYEE, DELETE_EMPLOYEE, EDIT_EMPLOYEE } from '../actiontypes/actiontypes';
 import axios from 'axios';
 
 export const getEmployees = () => {
 return dispatch => {
 return axios.get("http://localhost:3000/employees").then((response) => {
 console.log(response);
 dispatch({ type: GET_EMPLOYEES, payload: response.data });
 })
 }
 }

In this file, we are going to call the API to get a list of employees from our json-server API what we have created previously.

/src/redux/actiontypes/actiontypes.js
 export const GET_EMPLOYEES = "GET_EMPLOYEES";

This file is used to create different action types that we are going to use inside reducer to identify actions differently.

/src/redux/reducers/employeeReducer.js
 const employeeReducer = (state = [], action) => {
 
 switch (action.type) {
 case 'GET_EMPLOYEES':
 return action.payload;
 default:
 return state;
 }
 }
 export default employeeReducer;

In this file, we have created employee reducer, which is used to maintain the state of a different module and it will be located into single reducer called combined reducer.In order to create combined reducer, create a new file as described below.

/src/redux/reducers/index.js
 import { combineReducers } from 'redux';
 // Imported employee reducer
 import employeeReducer from './employeeReducer';
 
 const rootReducer = combineReducers({
 employee: employeeReducer,
 });
 
 export default rootReducer;

Now we are done with our important files related to Redux implementation, now we will create the component file which is used to list all the employee.

Step 5.

Create new folder inside src named components and create new file as described below. In which we are going to write code to list down the employee records

/src/components/GetEmployees.js
 import React, { Component } from 'react';
 import { connect } from 'react-redux';
 import { Card, Button, CardTitle, CardText, Row, Col, Table } from 'reactstrap';
 import { getEmployees } from '../redux/actions/actions';
 
 class GetEmployees extends Component {
 constructor(props) {
 super(props);
 this.state = {
 emps: []
 }
 }
 
 // To call get api of employee using actions file
 componentDidMount() {
 this.props.getEmployees();
 }
 
 // To render the list of employee
 render() {
 const employees = this.props.employee;
 console.log(employees);
 return (
 <Card body>
 <CardTitle>Employees</CardTitle>
 <CardText>
 <Table dark>
 <thead>
 <tr>
 <th>#</th>
 <th>Name</th>
 <th>User Name</th>
 <th>Email</th>
 <th>Phone</th>
 </tr>
 </thead>
 <tbody>
 {/* Iterate over employee records */}
 {employees.map((post) => (
 <tr key={post.id}>
 <th scope="row">{post.id}</th>
 <td>{post.firstName}</td>
 <td>{post.lastName}</td>
 <td>{post.email}</td>
 <td>{post.phone}</td>
 </tr>
 ))}
 </tbody>
 </Table>
 </CardText>
 </Card>
 );
 }
 }

 
 // Mapping of state to props to use it locally in this file
 const mapStateToProps = (state) => {
 return { employee: state.employee }
 }
 // Connecting this file with redux
 export default connect(mapStateToProps, { getEmployees })(GetEmployees);

In this file, I have implemented few things like.

  • When component mounted, our get API will be triggered and will fetch the results and all the records will be maintained inside employee reducer file.

  • After getting all the record, we will have all records will be stored in the current file’s props I mean to say properties, from where we can access a list of employees.

  • Inside render method, I have used different reactstrap components like Table, card, button to make the user interface clean yet simple.

  • And at last, we will connect our file to the redux so that will use all the state properties whenever we want.

Step 6.

So far, we have created and implemented all the necessary files, now its time to list down the record, for that we need to modify our app component which is the main entry point of our application.

/src/App.js
 import React, { Component } from 'react';
 import './index.css';
 // Bootstrap components
 import { Card, Button, CardTitle, CardText, Row, Col, Table } from 'reactstrap'
 // Importing GetEmployee file
 import GetEmployees from './components/GetEmployees';
 
 class App extends Component {
 render() {
 return (
 <div className="App">
 <div className="docs-example">
 <h1 className="post_heading">Using Redux with React</h1>
 <Row>
 <Col sm="12">
 {/* Includeing re-usable component */}
 <GetEmployees />
 </Col>
 </Row>
 </div>
 </div>
 );
 }
 }
 export default App;

I have just imported and added get employee component, so whenever our App.js comes into the picture, at a time GetEmployee component stars its action to render the list of records.

Step 7

Probably the last and important step because in this step, we are going to provide our combined reducer so that our state will be accessible to all the files which are connected to the redux using redux-thunk middleware.

/src/index.js
 import React from 'react';
 import ReactDOM from 'react-dom';
 import { Provider } from 'react-redux';
 import ReduxThunk from 'redux-thunk';
 import { createStore, applyMiddleware } from 'redux';
 import rootReducer from './redux/reducers/index';
 import App from './App';
 
 // To use bootstrap css
 import 'bootstrap/dist/css/bootstrap.min.css';
 
 // To apply middleware to the store
 const createStoreWithMiddleware = applyMiddleware(ReduxThunk)(createStore);
 
 // Providing root reducer to the app component
 ReactDOM.render(
 <Provider store={createStoreWithMiddleware(rootReducer)}>
 <App />
 </Provider>, 

 document.getElementById('root')
 );

Now we have completed almost all the configuration for the application using Redux, the last step is to execute the application and let's see how it works.

Step 8

To run our application, we need to use following npm command.

Npm start

And the same time, open new PowerShell window and change directory to /public where we have created the data.json file.

Json-server data.json

Open both tabs for front-end project as well as json-server API URL.

Output

And the same time, you can see the API is running into another tab like this.

This is how we have developed a simple demo with Redux and React using different file configuration.

Summary

In this two-part of tutorial series named Using Redux with React, we have learned different things which are listed below.

  • What is Redux

  • Different concepts of Redux

  • Why we can use Redux with React and its Advantages

  • Using Redux with React with Example

    I hope you get to something from this article, I would recommend you to go through source code attached to this article and try to implement different examples using Redux, Happy Learning.

Crack Your Technical Interview
 
Join Our Hands-on Training Programs

+