Create React App with MongoDB - Part 4 Connecting Backend with the Frontend

Part 4: Connecting backend with the frontend

Frontend and backend are ready. Let’s connect them.

Installing and using Axios

To connect both of them, we need the Axios library. Run the following command to install the Axios.

npm install axios

Then, import Axios in the details.js file.

import axios from "axios";

Completing the frontend

We will use the Axios to fetch data from the backend. We will use axios.get method. But first, we need to define a state in the constructor.

this.state = {
  data: [],
  buttonClicked: false
};

data: This will hold the details fetched from the backend. buttonClicked: This will be used to display data when the button is clicked.

This is axios is used.

axios.get("http://localhost:4000/getData").then(res => {
  this.setState({
    data: res.data
  });
});

We used the same endpoint that we defined while creating the backend. When we get the response from the backend, we have to store the data in a state. We will store the data in this.state.data.

To make this work properly, we will add this code in a lifecycle method known as componentDidMount(). This method executes before the first rendering.

componentDidMount(){
        axios.get('http://localhost:4000/getData')
        .then((res) =>{
         this.setState({
             data: res.data
         })
        });

    }

Display data

Now, we have all the data. We just need to display it. Remember, the data returned is an array of objects. We have to iterate through it. We will display the data in the following way.

        this.state.data.map((data)=>{
            return(
            <React.Fragment>
                <p> <b>name</b> : {data.name}</p>
                <p><b>age</b> : {data.age}</p>
                <hr/>
            </React.Fragment>
        )

Observe the code. We will iterate through this.state.data using the map method. Now we have to put this inside a condition. This code will only get executed when the button is clicked. And for this, we have this.state.buttonClicked.

getDetails(){

        if(!this.state.buttonClicked){
        this.setState({
            buttonClicked: true
        })
    }
    }

This function will be executed when the button is clicked. It will change the value of this.state.buttonClicked to true and then data will get displayed on the screen.

Let’s add everything to the details.js file.

import React, { Component } from "react";
import axios from "axios";

export default class Details extends Component {
  constructor() {
    super();
    this.state = {
      data: [],
      buttonClicked: false
    };
    this.getDetails = this.getDetails.bind(this);
  }

  componentDidMount() {
    axios.get("http://localhost:4000/getData").then(res => {
      this.setState({
        data: res.data
      });
    });
  }

  getDetails() {
    if (!this.state.buttonClicked) {
      this.setState({
        buttonClicked: true
      });
    }
  }

  render() {
    return (
      <div className="container-fluid" style={{ marginTop: "30px" }}>
        <div className="row">
          <div className="col-xs-12" style={{ textAlign: "center" }}>
            <button
              className="btn btn-primary"
              style={{ position: "absolute", marginLeft: "50%" }}
              onClick={this.getDetails}
            >
              Click
            </button>
            <div
              className="container-fluid"
              style={{
                position: "absolute",
                textAlign: "center",
                marginTop: "50px"
              }}
            >
              {this.state.buttonClicked
                ? this.state.data.map(data => {
                    return (
                      <React.Fragment>
                        <p>
                          {" "}
                          <b>name</b> : {data.name}
                        </p>
                        <p>
                          <b>age</b> : {data.age}
                        </p>
                        <hr />
                      </React.Fragment>
                    );
                  })
                : null}
            </div>
          </div>
        </div>
      </div>
    );
  }
}

This is how details.js file looks now.

Running the application.

The frontend is ready, the backend is ready, and both are connected. Let’s see how it looks in the browser.

Image from Gyazo

Let’s click on the button.

Image from Gyazo

Everything works great!

Conclusion

So we created a simple web application using the MERN stack. First, we created the backend using Node.js, mongoose, and MongoDB. Then, we created the frontend using React. Finally, we connected both of them using the Axios library.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.