HI WELCOME TO SIRIS

Getting Started With React Redux : Part2

Leave a Comment
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
  1. {
  2. "employees": [
  3. {
  4. "firstName": "Manavv",
  5. "lastName": "Pandya",
  6. "email": "manav@gmail.com",
  7. "phone": "12345678910",
  8. "id": 1
  9. },
  10. {
  11. "firstName": "test",
  12. "lastName": "test",
  13. "email": "a@b.com",
  14. "phone": "12345678910",
  15. "id": 2
  16. },
  17. {
  18. "firstName": "test1",
  19. "lastName": "test1",
  20. "email": "a123@b.com",
  21. "phone": "12345678910",
  22. "id": 3
  23. },
  24. {
  25. "firstName": "test2",
  26. "lastName": "test2",
  27. "email": "a1234@b.com",
  28. "phone": "12345678910",
  29. "id": 4
  30. },
  31. {
  32. "firstName": "test3",
  33. "lastName": "test3",
  34. "email": "a12345@b.com",
  35. "phone": "12345678910",
  36. "id": 5
  37. }
  38. ]
  39. }
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
  1. import { GET_EMPLOYEES, ADD_EMPLOYEE, DELETE_EMPLOYEE, EDIT_EMPLOYEE } from '../actiontypes/actiontypes';
  2. import axios from 'axios';
  3. export const getEmployees = () => {
  4. return dispatch => {
  5. return axios.get("http://localhost:3000/employees").then((response) => {
  6. console.log(response);
  7. dispatch({ type: GET_EMPLOYEES, payload: response.data });
  8. })
  9. }
  10. }
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
  1. 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
  1. const employeeReducer = (state = [], action) => {
  2. switch (action.type) {
  3. case 'GET_EMPLOYEES':
  4. return action.payload;
  5. default:
  6. return state;
  7. }
  8. }
  9. 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
  1. import { combineReducers } from 'redux';
  2. // Imported employee reducer
  3. import employeeReducer from './employeeReducer';
  4. const rootReducer = combineReducers({
  5. employee: employeeReducer,
  6. });
  7. 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
  1. import React, { Component } from 'react';
  2. import { connect } from 'react-redux';
  3. import { Card, Button, CardTitle, CardText, Row, Col, Table } from 'reactstrap';
  4. import { getEmployees } from '../redux/actions/actions';
  5. class GetEmployees extends Component {
  6. constructor(props) {
  7. super(props);
  8. this.state = {
  9. emps: []
  10. }
  11. }
  12. // To call get api of employee using actions file
  13. componentDidMount() {
  14. this.props.getEmployees();
  15. }
  16. // To render the list of employee
  17. render() {
  18. const employees = this.props.employee;
  19. console.log(employees);
  20. return (
  21. <Card body>
  22. <CardTitle>Employees</CardTitle>
  23. <CardText>
  24. <Table dark>
  25. <thead>
  26. <tr>
  27. <th>#</th>
  28. <th>Name</th>
  29. <th>User Name</th>
  30. <th>Email</th>
  31. <th>Phone</th>
  32. </tr>
  33. </thead>
  34. <tbody>
  35. {/* Iterate over employee records */}
  36. {employees.map((post) => (
  37. <tr key={post.id}>
  38. <th scope="row">{post.id}</th>
  39. <td>{post.firstName}</td>
  40. <td>{post.lastName}</td>
  41. <td>{post.email}</td>
  42. <td>{post.phone}</td>
  43. </tr>
  44. ))}
  45. </tbody>
  46. </Table>
  47. </CardText>
  48. </Card>
  49. );
  50. }
  51. }
  52.  
  53. // Mapping of state to props to use it locally in this file
  54. const mapStateToProps = (state) => {
  55. return { employee: state.employee }
  56. }
  57. // Connecting this file with redux
  58. 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
  1. import React, { Component } from 'react';
  2. import './index.css';
  3. // Bootstrap components
  4. import { Card, Button, CardTitle, CardText, Row, Col, Table } from 'reactstrap'
  5. // Importing GetEmployee file
  6. import GetEmployees from './components/GetEmployees';
  7. class App extends Component {
  8. render() {
  9. return (
  10. <div className="App">
  11. <div className="docs-example">
  12. <h1 className="post_heading">Using Redux with React</h1>
  13. <Row>
  14. <Col sm="12">
  15. {/* Includeing re-usable component */}
  16. <GetEmployees />
  17. </Col>
  18. </Row>
  19. </div>
  20. </div>
  21. );
  22. }
  23. }
  24. 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
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import { Provider } from 'react-redux';
  4. import ReduxThunk from 'redux-thunk';
  5. import { createStore, applyMiddleware } from 'redux';
  6. import rootReducer from './redux/reducers/index';
  7. import App from './App';
  8. // To use bootstrap css
  9. import 'bootstrap/dist/css/bootstrap.min.css';
  10. // To apply middleware to the store
  11. const createStoreWithMiddleware = applyMiddleware(ReduxThunk)(createStore);
  12. // Providing root reducer to the app component
  13. ReactDOM.render(
  14. <Provider store={createStoreWithMiddleware(rootReducer)}>
  15. <App />
  16. </Provider>,
  17.  
  18. document.getElementById('root')
  19. );
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.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.