React.js CRUD example to consume Web API

In this tutorial, I will show you how to build a React.js CRUD Application to consume Web API, display and modify data with Router, Axios & Bootstrap.

Fullstack:
React + Spring Boot + MySQL: CRUD example
React + Spring Boot + PostgreSQL: CRUD example
React + Spring Boot + MongoDB: CRUD example
React + Node.js + Express + MySQL: CRUD example
React + Node.js + Express + PostgreSQL example
React + Node.js + Express + MongoDB example
React + Django + Rest Framework example

Related Posts:
React File Upload with Axios and Progress Bar to Rest API
React JWT Authentication (without Redux) example
React Redux: JWT Authentication example
– Typescript version: React Typescript example Project with Axios and Web API

The example using React Hooks:
React Hooks CRUD example with Axios and Web API

Or Redux: React Redux CRUD App example with Rest API

Serverless:
React Firebase CRUD with Realtime Database
React Firestore CRUD App example | Firebase Cloud Firestore

Overview of React.js CRUD App example with Web API

We will build a React Tutorial Application in that:

  • Each Tutorial has id, title, description, published status.
  • We can create, retrieve, update, delete Tutorials.
  • There is a Search bar for finding Tutorials by title.

Here are screenshots of our React CRUD Application.

– Create an item:

react-crud-example-web-api-demo-create

If you want to implement Form Validation, please visit:
React Form Validation example

– Retrieve all items:

react-crud-example-web-api-demo-retrieve

– Click on Edit button to update an item:

react-crud-example-web-api-demo-retrieve-one

On this Page, you can:

  • change status to Published using Publish button
  • delete the item using Delete button
  • update the item details with Update button

react-crud-example-web-api-demo-update

– Search Tutorials by title:

react-crud-example-web-api-demo-search

This React Client consumes the following Web API:

Methods Urls Actions
POST /api/tutorials create new Tutorial
GET /api/tutorials retrieve all Tutorials
GET /api/tutorials/:id retrieve a Tutorial by :id
PUT /api/tutorials/:id update a Tutorial by :id
DELETE /api/tutorials/:id delete a Tutorial by :id
DELETE /api/tutorials delete all Tutorials
GET /api/tutorials?title=[keyword] find all Tutorials which title contains keyword

You can find step by step to build a Server like this in one of these posts:
Express, Sequelize & MySQL
Express, Sequelize & PostgreSQL
Express, Sequelize & SQL Server
Express & MongoDb
Spring Boot & MySQL
Spring Boot & PostgreSQL
Spring Boot & MongoDB
Spring Boot & SQL Server
Spring Boot & H2
Spring Boot & Cassandra
Spring Boot & Oracle
Python/Django & MySQL
Python/Django & PostgreSQL
Python/Django & MongoDB

React.js App Component Diagram with Router & Axios

Now look at the React components that we’re gonna implement:

react-crud-example-web-api-components

– The App component is a container with React Router. It has navbar that links to routes paths.

TutorialsList component gets and displays Tutorials.
Tutorial component has form for editing Tutorial’s details based on :id.
AddTutorial component has form for submission new Tutorial.

– These Components call TutorialDataService methods which use axios to make HTTP requests and receive responses.

Technology

  • React 18/17
  • react-router-dom 6
  • axios 0.27.2
  • bootstrap 4.6.2

Project Structure

react-crud-example-web-api-project-structure

I’m gonna explain it briefly.

package.json contains 4 main modules: react, react-router-dom, axios & bootstrap.
App is the container that has Router & navbar.
– There are 3 components: TutorialsList, Tutorial, AddTutorial.
http-common.js initializes axios with HTTP base Url and headers.
TutorialDataService has methods for sending HTTP requests to the Apis.
.env configures port for this React CRUD App.

Setup React.js Project

Open cmd at the folder you want to save Project folder, run command:
npx create-react-app react-crud

After the process is done. We create additional folders and files like the following tree:


public

src

components

add-tutorial.component.js

tutorial.component.js

tutorials-list.component.js

services

tutorial.service.js

App.css

App.js

index.js

package.json


Import Bootstrap to React CRUD App

Run command: npm install bootstrap.

Open src/App.js and modify the code inside it as following-

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";

class App extends Component {
  render() {
    // ...
  }
}

export default App;

Add React Router to React CRUD App

– Run the command: npm install react-router-dom.
– Open src/index.js and wrap App component by BrowserRouter object.

import React from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";

import App from "./App";

const container = document.getElementById("root");
const root = createRoot(container);

root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

From the react-router-dom v6, the support for props.match.params or props.history has been deprecated. So we need a wrapper (HOC) that can use new useful hooks.

In src folder, create common/with-router.js file with following code:

import { useLocation, useNavigate, useParams } from "react-router-dom";

export const withRouter = (Component) => {
  function ComponentWithRouterProp(props) {
    let location = useLocation();
    let navigate = useNavigate();
    let params = useParams();
    return <Component {...props} router={{ location, navigate, params }} />;
  }
  return ComponentWithRouterProp;
};

Add Navbar to React CRUD App

Open src/App.js, this App component is the root container for our application, it will contain a navbar, and also, a Routes object with several Route. Each Route points to a React Component.

import React, { Component } from "react";
import { Routes, Route, Link } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";

import AddTutorial from "./components/add-tutorial.component";
import Tutorial from "./components/tutorial.component";
import TutorialsList from "./components/tutorials-list.component";

class App extends Component {
  render() {
    return (
      <div>
        <nav className="navbar navbar-expand navbar-dark bg-dark">
          <Link to={"/tutorials"} className="navbar-brand">
            bezKoder
          </Link>
          <div className="navbar-nav mr-auto">
            <li className="nav-item">
              <Link to={"/tutorials"} className="nav-link">
                Tutorials
              </Link>
            </li>
            <li className="nav-item">
              <Link to={"/add"} className="nav-link">
                Add
              </Link>
            </li>
          </div>
        </nav>

        <div className="container mt-3">
          <Routes>
            <Route path="/" element={<TutorialsList/>} />
            <Route path="/tutorials" element={<TutorialsList/>} />
            <Route path="/add" element={<AddTutorial/>} />
            <Route path="/tutorials/:id" element={<Tutorial/>} />
          </Routes>
        </div>
      </div>
    );
  }
}

export default App;

Initialize Axios for React CRUD HTTP Client

Let’s install axios with command: npm install axios.
Under src folder, we create http-common.js file with following code:

import axios from "axios";

export default axios.create({
  baseURL: "http://localhost:8080/api",
  headers: {
    "Content-type": "application/json"
  }
});

You can change the baseURL that depends on REST APIs url that your Server configures.

For more details about ways to use Axios, please visit:
Axios request: Get/Post/Put/Delete example

Create Data Service

In this step, we’re gonna create a service that uses axios object above to send HTTP requests.

services/tutorial.service.js

import http from "../http-common";

class TutorialDataService {
  getAll() {
    return http.get("/tutorials");
  }

  get(id) {
    return http.get(`/tutorials/${id}`);
  }

  create(data) {
    return http.post("/tutorials", data);
  }

  update(id, data) {
    return http.put(`/tutorials/${id}`, data);
  }

  delete(id) {
    return http.delete(`/tutorials/${id}`);
  }

  deleteAll() {
    return http.delete(`/tutorials`);
  }

  findByTitle(title) {
    return http.get(`/tutorials?title=${title}`);
  }
}

export default new TutorialDataService();

We call axios get, post, put, delete method corresponding to HTTP Requests: GET, POST, PUT, DELETE to make CRUD Operations.

You can simplify import statement with:
Absolute Import in React

Create React Components

Now we’re gonna build 3 components corresponding to 3 Routes defined before.

Add item Component

This component has a Form to submit new Tutorial with 2 fields: title & description.

react-crud-example-web-api-demo-create

components/add-tutorial.component.js

import React, { Component } from "react";
import TutorialDataService from "../services/tutorial.service";

export default class AddTutorial extends Component {
  constructor(props) {
    super(props);
    this.onChangeTitle = this.onChangeTitle.bind(this);
    this.onChangeDescription = this.onChangeDescription.bind(this);
    this.saveTutorial = this.saveTutorial.bind(this);
    this.newTutorial = this.newTutorial.bind(this);

    this.state = {
      id: null,
      title: "",
      description: "", 
      published: false,

      submitted: false
    };
  }

  onChangeTitle(e) {
    this.setState({
      title: e.target.value
    });
  }

  onChangeDescription(e) {
    this.setState({
      description: e.target.value
    });
  }

  saveTutorial() {
    var data = {
      title: this.state.title,
      description: this.state.description
    };

    TutorialDataService.create(data)
      .then(response => {
        this.setState({
          id: response.data.id,
          title: response.data.title,
          description: response.data.description,
          published: response.data.published,

          submitted: true
        });
        console.log(response.data);
      })
      .catch(e => {
        console.log(e);
      });
  }

  newTutorial() {
    this.setState({
      id: null,
      title: "",
      description: "",
      published: false,

      submitted: false
    });
  }

  render() {
    // ...
  }
}

First, we define the constructor and set initial state, bind this to the different events.

Because there are 2 fields, so we create 2 functions to track the values of the input and set that state for changes. We also have a function to get value of the form (state) and send the POST request to the Web API. It calls TutorialDataService.create() method.

For render() method, we check the submitted state, if it is true, we show Add button for creating new Tutorial again. Otherwise, a Form will display.

export default class AddTutorial extends Component {
  // ...

  render() {
    return (
      <div className="submit-form">
        {this.state.submitted ? (
          <div>
            <h4>You submitted successfully!</h4>
            <button className="btn btn-success" onClick={this.newTutorial}>
              Add
            </button>
          </div>
        ) : (
          <div>
            <div className="form-group">
              <label htmlFor="title">Title</label>
              <input
                type="text"
                className="form-control"
                id="title"
                required
                value={this.state.title}
                onChange={this.onChangeTitle}
                name="title"
              />
            </div>

            <div className="form-group">
              <label htmlFor="description">Description</label>
              <input
                type="text"
                className="form-control"
                id="description"
                required
                value={this.state.description}
                onChange={this.onChangeDescription}
                name="description"
              />
            </div>

            <button onClick={this.saveTutorial} className="btn btn-success">
              Submit
            </button>
          </div>
        )}
      </div>
    );
  }
}

List of items Component

This component has:

  • a search bar for finding Tutorials by title.
  • a tutorials array displayed as a list on the left.
  • a selected Tutorial which is shown on the right.

react-crud-example-web-api-demo-retrieve

So we will have following state:

  • searchTitle
  • tutorials
  • currentTutorial and currentIndex

We also need to use 3 TutorialDataService methods:

  • getAll()
  • deleteAll()
  • findByTitle()

components/tutorials-list.component.js

import React, { Component } from "react";
import TutorialDataService from "../services/tutorial.service";
import { Link } from "react-router-dom";

export default class TutorialsList extends Component {
  constructor(props) {
    super(props);
    this.onChangeSearchTitle = this.onChangeSearchTitle.bind(this);
    this.retrieveTutorials = this.retrieveTutorials.bind(this);
    this.refreshList = this.refreshList.bind(this);
    this.setActiveTutorial = this.setActiveTutorial.bind(this);
    this.removeAllTutorials = this.removeAllTutorials.bind(this);
    this.searchTitle = this.searchTitle.bind(this);

    this.state = {
      tutorials: [],
      currentTutorial: null,
      currentIndex: -1,
      searchTitle: ""
    };
  }

  componentDidMount() {
    this.retrieveTutorials();
  }

  onChangeSearchTitle(e) {
    const searchTitle = e.target.value;

    this.setState({
      searchTitle: searchTitle
    });
  }

  retrieveTutorials() {
    TutorialDataService.getAll()
      .then(response => {
        this.setState({
          tutorials: response.data
        });
        console.log(response.data);
      })
      .catch(e => {
        console.log(e);
      });
  }

  refreshList() {
    this.retrieveTutorials();
    this.setState({
      currentTutorial: null,
      currentIndex: -1
    });
  }

  setActiveTutorial(tutorial, index) {
    this.setState({
      currentTutorial: tutorial,
      currentIndex: index
    });
  }

  removeAllTutorials() {
    TutorialDataService.deleteAll()
      .then(response => {
        console.log(response.data);
        this.refreshList();
      })
      .catch(e => {
        console.log(e);
      });
  }

  searchTitle() {
    TutorialDataService.findByTitle(this.state.searchTitle)
      .then(response => {
        this.setState({
          tutorials: response.data
        });
        console.log(response.data);
      })
      .catch(e => {
        console.log(e);
      });
  }

  render() {
    // ...
  }
}

Let’s continue to implement render() method:

// ...
import { Link } from "react-router-dom";

export default class TutorialsList extends Component {
  // ...

  render() {
    const { searchTitle, tutorials, currentTutorial, currentIndex } = this.state;

    return (
      <div className="list row">
        <div className="col-md-8">
          <div className="input-group mb-3">
            <input
              type="text"
              className="form-control"
              placeholder="Search by title"
              value={searchTitle}
              onChange={this.onChangeSearchTitle}
            />
            <div className="input-group-append">
              <button
                className="btn btn-outline-secondary"
                type="button"
                onClick={this.searchTitle}
              >
                Search
              </button>
            </div>
          </div>
        </div>
        <div className="col-md-6">
          <h4>Tutorials List</h4>

          <ul className="list-group">
            {tutorials &&
              tutorials.map((tutorial, index) => (
                <li
                  className={
                    "list-group-item " +
                    (index === currentIndex ? "active" : "")
                  }
                  onClick={() => this.setActiveTutorial(tutorial, index)}
                  key={index}
                >
                  {tutorial.title}
                </li>
              ))}
          </ul>

          <button
            className="m-3 btn btn-sm btn-danger"
            onClick={this.removeAllTutorials}
          >
            Remove All
          </button>
        </div>
        <div className="col-md-6">
          {currentTutorial ? (
            <div>
              <h4>Tutorial</h4>
              <div>
                <label>
                  <strong>Title:</strong>
                </label>{" "}
                {currentTutorial.title}
              </div>
              <div>
                <label>
                  <strong>Description:</strong>
                </label>{" "}
                {currentTutorial.description}
              </div>
              <div>
                <label>
                  <strong>Status:</strong>
                </label>{" "}
                {currentTutorial.published ? "Published" : "Pending"}
              </div>

              <Link
                to={"/tutorials/" + currentTutorial.id}
                className="badge badge-warning"
              >
                Edit
              </Link>
            </div>
          ) : (
            <div>
              <br />
              <p>Please click on a Tutorial...</p>
            </div>
          )}
        </div>
      </div>
    );
  }
}

If you click on Edit button of any Tutorial, the app will direct you to Tutorial page.
We use React Router Link for accessing that page with url: /tutorials/:id.

You can add Pagination to this Component, just follow instruction in the post:
React Pagination with API using Material-UI

Item details Component

We’re gonna use the component lifecycle method: componentDidMount() to fetch the data from the Web API.

react-crud-example-web-api-demo-retrieve-one

For getting data & update, delete the Tutorial, this component will use 3 TutorialDataService methods:

  • get()
  • update()
  • delete()

Because we will get the params: props.router.params.id, so don’t forget to wrap this component with withRouter.

components/tutorial.component.js

import React, { Component } from "react";
import TutorialDataService from "../services/tutorial.service";
import { withRouter } from '../common/with-router';

class Tutorial extends Component {
  constructor(props) {
    super(props);
    this.onChangeTitle = this.onChangeTitle.bind(this);
    this.onChangeDescription = this.onChangeDescription.bind(this);
    this.getTutorial = this.getTutorial.bind(this);
    this.updatePublished = this.updatePublished.bind(this);
    this.updateTutorial = this.updateTutorial.bind(this);
    this.deleteTutorial = this.deleteTutorial.bind(this);

    this.state = {
      currentTutorial: {
        id: null,
        title: "",
        description: "",
        published: false
      },
      message: ""
    };
  }

  componentDidMount() {
    this.getTutorial(this.props.router.params.id);
  }

  onChangeTitle(e) {
    const title = e.target.value;

    this.setState(function(prevState) {
      return {
        currentTutorial: {
          ...prevState.currentTutorial,
          title: title
        }
      };
    });
  }

  onChangeDescription(e) {
    const description = e.target.value;
    
    this.setState(prevState => ({
      currentTutorial: {
        ...prevState.currentTutorial,
        description: description
      }
    }));
  }

  getTutorial(id) {
    TutorialDataService.get(id)
      .then(response => {
        this.setState({
          currentTutorial: response.data
        });
        console.log(response.data);
      })
      .catch(e => {
        console.log(e);
      });
  }

  updatePublished(status) {
    var data = {
      id: this.state.currentTutorial.id,
      title: this.state.currentTutorial.title,
      description: this.state.currentTutorial.description,
      published: status
    };

    TutorialDataService.update(this.state.currentTutorial.id, data)
      .then(response => {
        this.setState(prevState => ({
          currentTutorial: {
            ...prevState.currentTutorial,
            published: status
          }
        }));
        console.log(response.data);
      })
      .catch(e => {
        console.log(e);
      });
  }

  updateTutorial() {
    TutorialDataService.update(
      this.state.currentTutorial.id,
      this.state.currentTutorial
    )
      .then(response => {
        console.log(response.data);
        this.setState({
          message: "The tutorial was updated successfully!"
        });
      })
      .catch(e => {
        console.log(e);
      });
  }

  deleteTutorial() {    
    TutorialDataService.delete(this.state.currentTutorial.id)
      .then(response => {
        console.log(response.data);
        this.props.router.navigate('/tutorials');
      })
      .catch(e => {
        console.log(e);
      });
  }

  render() {
    // ...
  }
}

export default withRouter(Tutorial);

And this is the code for render() method:

class Tutorial extends Component {
  // ...

  render() {
    const { currentTutorial } = this.state;

    return (
      <div>
        {currentTutorial ? (
          <div className="edit-form">
            <h4>Tutorial</h4>
            <form>
              <div className="form-group">
                <label htmlFor="title">Title</label>
                <input
                  type="text"
                  className="form-control"
                  id="title"
                  value={currentTutorial.title}
                  onChange={this.onChangeTitle}
                />
              </div>
              <div className="form-group">
                <label htmlFor="description">Description</label>
                <input
                  type="text"
                  className="form-control"
                  id="description"
                  value={currentTutorial.description}
                  onChange={this.onChangeDescription}
                />
              </div>

              <div className="form-group">
                <label>
                  <strong>Status:</strong>
                </label>
                {currentTutorial.published ? "Published" : "Pending"}
              </div>
            </form>

            {currentTutorial.published ? (
              <button
                className="badge badge-primary mr-2"
                onClick={() => this.updatePublished(false)}
              >
                UnPublish
              </button>
            ) : (
              <button
                className="badge badge-primary mr-2"
                onClick={() => this.updatePublished(true)}
              >
                Publish
              </button>
            )}

            <button
              className="badge badge-danger mr-2"
              onClick={this.deleteTutorial}
            >
              Delete
            </button>

            <button
              type="submit"
              className="badge badge-success"
              onClick={this.updateTutorial}
            >
              Update
            </button>
            <p>{this.state.message}</p>
          </div>
        ) : (
          <div>
            <br />
            <p>Please click on a Tutorial...</p>
          </div>
        )}
      </div>
    );
  }
}

export default withRouter(Tutorial);

Add CSS style for React Components

Open src/App.css and write some CSS code as following:

.list {
  text-align: left;
  max-width: 750px;
  margin: auto;
}

.submit-form {
  max-width: 300px;
  margin: auto;
}

.edit-form {
  max-width: 300px;
  margin: auto;
}

Configure Port for React CRUD Client with Web API

Because most of HTTP Server use CORS configuration that accepts resource sharing retrictted to some sites or ports, so we also need to configure port for our App.

In project folder, create .env file with following content:

PORT=8081

Now we’ve set our app running at port 8081.

Run React CRUD App

You can run our App with command: npm start.
If the process is successful, open Browser with Url: http://localhost:8081/ and check it.

This React Client will work well with following back-end Rest APIs:
Express, Sequelize & MySQL
Express, Sequelize & PostgreSQL
Express, Sequelize & SQL Server
Express & MongoDb
Spring Boot & MySQL
Spring Boot & PostgreSQL
Spring Boot & MongoDB
Spring Boot & SQL Server
Spring Boot & H2
Spring Boot & Cassandra
Spring Boot & Oracle
Python/Django & MySQL
Python/Django & PostgreSQL
Python/Django & MongoDB

This is the demo video with brief instruction:

Conclusion

Today we’ve built a React CRUD Application successfully with React Router & Axios. Now we can consume REST APIs, display, search and modify data in a clean way. I hope you can make API call (GET/POST/PUT/DELETE) in your project at ease.

If you want to make the example use React Hooks, you can find it here:
React Hooks CRUD example with Axios and Web API

Implement Security:
React JWT Authentication (without Redux) example
React Redux: JWT Authentication example

Or you can add Pagination Component:
React Pagination with API using Material-UI

react-pagination-with-api-material-ui-change-page

Happy learning, see you again!

Further Reading

For more details about ways to use Axios, please visit:
Axios request: Get/Post/Put/Delete example

If you want to implement Form Validation:
React Form Validation example

Serverless with Firebase:
React Firebase CRUD with Realtime Database
React Firestore CRUD App example | Firebase Cloud Firestore

Using Material UI instead of Bootstrap:
React Material UI examples with a CRUD Application

Integration:
Integrate React with Spring Boot
Integrate React with Node.js Express

Source Code

You can find the complete source code for this tutorial on Github.

Typescript version: React Typescript example Project with Axios and Web API

80 thoughts to “React.js CRUD example to consume Web API”

  1. I visited various blogs however your React tutorials quality are is actually fabulous. Thanks for your effort!

  2. Thanks so much for such a wonderful write-up!

    Everything works great on my development machine (running mysql server, the API, and React), but when I try to use it from another machine on my LAN (by going to 192.168.x.x:8081), none of my data populates.

    How can I correct this securely?

    Thanks again!

  3. I really appreciate your content and tutorials. The React articles is really well-written.

  4. hello all
    please, what is the function of these lines:
    this.onChangeTitle = this.onChangeTitle.bind(this);
    this.onChangeDescription = this.onChangeDescription.bind(this);
    this.getTutorial = this.getTutorial.bind(this);
    this.updatePublished = this.updatePublished.bind(this);
    this.updateTutorial = this.updateTutorial.bind(this);
    this.deleteTutorial = this.deleteTutorial.bind(this);

  5. I learned a lot from your website. This’s the 5 or 6th project I worked on, with full-stack and all working fine.
    Also your code is well explained.
    I’m really appreciated
    Github => Star, YouTube => Like 🙂

  6. Hello,

    Im new to the MEAN stack, it is so much to choose.
    Can you help me out ? I must build an CRUD application which also needs to be responsive, this all must be build in the Front-end. But what should I use ? React + Node.js ? Angular + Node.js? I figured out that the node js is best for data handling between front end and Database. Please help me ?

  7. Hi, may I know why the “required” does not display any warning to the users? I figured that I needed to add to trigger the message display for “required”, however, it will automatically refreshes to the new form after submit. Please help how to solve this. Your help is very highly appreciated. Thanks

  8. Thank you – this is an excellent run through. And I love your alternatives using different stacks. Much appreciated!

  9. Hi,
    I followed this guide and it works perfectly until I try to insert data to db. Then I get a 404 error for routes not found.
    What’s the problem?
    Thanks!

        1. Please download github source code in the tutorials and compare with your code. I’ve tested and they work well.

  10. HI nice tutorial but when i integrate on my local machine then i govt an error “Failed to load resource: net::ERR_EMPTY_RESPONSE”

  11. Hey, I would like to appreciate this tutorial. You did great work. But I get an error. To check I added some data into the database. That data will be listed. But when I tried to insert the data, they are not inserted into DB.

    This is my inspect.

    add:1 Access to XMLHttpRequest at ‘http://localhost:8080/api/tutorials’ from origin ‘http://localhost:8081’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

    I can’t understand where is the error.
    So help me.

  12. Hi, I have one problem so I will be so thankful if you can help me. When I click on Tutorial and go on Edit button my URL is like this: /tutorials/null instead of /tutorials/id of the product.

    Thank you!

  13. HI,

    I am getting the error while running npm start

    ×
    Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

    5 | import App from ‘./App’;
    6 | import * as serviceWorker from ‘./serviceWorker’;
    7 |
    > 8 | ReactDOM.render(
    9 |
    10 |
    11 | ,

    Any idea why? Thanks in advance

    1. you must run this command:
      npx create-react-app react-crud –template cra-template-pwa

      this command crear the proyect and service-worker.js file into /src, after change name to serviceWorker.js

  14. Thank you very much Bezkoder, great tutorials!
    I try to follow your tutorials, My backend run very well. But in the front, an error is comming when I try to submit a tutorial.
    “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/api/tutorials. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://localhost:8081’)”. I don’t know what is the problem please help me .
    Thank you!

  15. Hi, I get this error when running. Any idea why?

    TypeError: tutorials.map is not a function

    112 |
    113 | Tutorials List
    114 |
    > 115 |
    | ^ 116 | {tutorials &&
    117 | tutorials.map((tutorial, index) => (
    118 | <li

      1. Hi Bezkoder,
        I also had the same issue and couldn’t find a solution yet. If possible can you elaborate more on how to fix it?

        Thanks in advance.

        1. I’m having the same issue and i’m pretty sure I have the dataset right. Is there a sample of the data payload that can be shared or a working version of this online somewhere? The data payload has to be what it is. Thoughts? Great tutorial, thanks!

      1. Hi, excuse me, I think I have the same error, I can add things to the db (add tutorials works) but it doesn’t show any tutorials,

        Error: Request failed with status code 500
        createError createError.js:16
        settle settle.js:17
        handleLoad xhr.js:61

        My guess is that it is a backend problem, but im not sure how to fix it.

        Sorry to bother you u.u

        1. I had problems with the backend running under localhost instead I gave it the external IP of the server on both the backend allow section and the http-common section and it started working. I am still looking into why I suspect it might have something to do with the IP’s that the Backend / API server is running on.

      2. I dont know what I have done, but it is ok my backend and frontend is running smoothly. thanks

  16. I noticed that you created a file called serviceWorker and referenced it in the src/index.js file. However the tutorial does not say what should be in that file. Is that a file that should have been created by default once react is installed? If that is the case, then that file was not automatically created after running npx create-react-app

    1. I was able to see the webpage after commenting out the lines associated with serviceWorker. However I’m not able to see the list of entries. I have tested the api with Postman and it works. The error from the browser console is:
      Error: Request failed with status code 500
      createError createError.js:16
      settle settle.js:17
      handleLoad xhr.js:61

      1. I fix the previous error by correcting the base url in the http-commons file. Whilst doing further testing I am getting an error when trying to update, although the database gets updated.
        Browser Error: Request failed with status code 400
        Server Error: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client.

        1. Fixed: Anyone who may have come across this error. It’s because 2 or more responses were sent with possibly the same status code. That was my error in the update function on the server side.

    2. you must install this comand:

      npx create-react-app react-crud –template cra-template-pwa

      this command create file service-worker.js into /src, after change name for serviceWorker.js

    1. Yes, the source code for frontend in the tutorial. For backend, please visit reference links.

  17. Hey Bezkoder, love the tutorial.

    That said, I’m getting an error with the server : ‘:8080/tutorials:1 Failed to load resource: net::ERR_CONNECTION_REFUSED’

    And when I try to post an entry I get ‘POST http://localhost:8080/tutorials net::ERR_CONNECTION_REFUSED’

    My server by default runs at port 3000 and I’ve tried switching ports around with the same issue.

    Any idea what to do here? Thanks in advance!

  18. I was struggling a lot in learning full stack in react. Every tutorials seems to be difficult to me. But this is one simple tutorial that i have understood very well. Thank you so much bezKoder. Your tutorials are well understood.

  19. Hi,
    First of all thank you for an awesome tutorial! 🙂
    Now I want to ask something. My front end and back end both are working but not together. When I try to create a new tutorial using front end, it doesn’t get added to the database. I just wanna ask what is the exact structure of these two? Like do we have to create the back end folder inside of front end or it should be outside? Does this thing affects the working of front end?
    Kindly reply ASAP!
    Thanks! 🙂

      1. Hi,
        It is showing the following error:

        index.js:1 Warning: Invalid DOM property `class`. Did you mean `className`?
        in button (created by Button)
        in Button (at App.js:50)
        in Router (created by BrowserRouter)
        in BrowserRouter (at App.js:14)
        in App (at src/index.js:10)
        in Router (created by BrowserRouter)
        in BrowserRouter (at src/index.js:9)

        1. Hi, please check any place in your project where you used class="". You should change to className="".

  20. Congratulation bezkoder!
    Awesome work. This is one of a very few tutorial that works without a single glitch. Not only it did not have a glitch, but it’s very clear and easy to follow.
    Keep up the great the work.

  21. Bro wow. Crystal clear. All things has run in one go. Dude you are truly champion. I am going to follow all your tutorials.

  22. BezKoder Jedi.
    Please! Can you upgrade this project with others DOM elements (select, radio, checkbox)? It’ll very interesting.

  23. I sort of figured it out, I was testing in IE… which just shows a blank page. When I run the front end in chrome it’s fine. I’m not sure why this is.

  24. Thanks for the tutorials bezkoder! I got the back end working fine and tested it with postman, everything works fine but when I try to run the front end I just get a blank screen. I made sure there were records in the database and tested it again with postman. I left all the settings as they were in your tutorials. Is there something I’m not configuring right?

  25. Thank you very much ,your React and Node tutorial are very helpful for me, but I have a problem, i run the backend with node server.js and i call localhost:8080 and i run the frontend with npm start but when i try to ad a new tutorial it doesn’t work i don’t found it in mysql DB and also the list of tutorials doensn’t showen , the front and back are not relited despite i run both of them . i don’t know what is the problem please help me .
    Thank you

    1. Hi, please show me more details about your issue. Did you test the backend with HTTP Client like Postman?

  26. Great tutorials! Thank you very much Bezkoder!
    Following your tutorials, My codes run very well. Just one more thing:
    How can I modify the code so that the web can be visited in the local network?
    I have successfully changed some codes so that both the backend APIs and frontend codes can be visited by another client in the local network, but it seems that the frontend codes didn’t get the JSON data from the backend APIs.
    Can you tell me where the problem is, and how I can fix it?

      1. Since McAfee is running in port 8081, I changed the web interface to run in 8082. Backend was expecting the calls from 8081. I fixed the cors configuration in backend to point to 8082. Worked like a charm. Thanks.

  27. Hi bezkoder,

    I can’t see your tutorial for backend servers. could you please put here? Thanks!

    1. Hi, you can find it in fullstack tutorials at the beginning of this post. 🙂

  28. Your React tutorial is very good, but I have a little problem, when I run it on the server, nothing appears, I have already checked the entire code structure and follow what was done by you.

    1. Hi, you should run one of the backend servers that I introduced in the tutorial first. The frontend won’t work alone 🙂

Comments are closed to reduce spam. If you have any question, please send me an email.