Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

React HTTP request example.

In this chapter, you will about how to send an HTTP request to the backend APIs with an example. Now for connecting with a server API, we can use the axios package, this is an npm package that comes with a lot of features

Make XMLHttpRequests from the browser
Make HTTP requests from node.js
Supports the Promise API
Intercept request and response
Transform request and response data
Cancel requests
Automatic transforms for JSON data
Client-side support for protecting against XSRF

Now we will write an example to how to make an HTTP request which makes a get request and returns a data. We are using the same dummy data providers like JSONPlaceholder. You can use the URL https://jsonplaceholder.typicode.com/users for getting the users data. Now the question is in which lifecycle the HTTP request should be initiated, you can make an HTTP request to the server in the lifecycle hook componentDidMount().

In the manager component, we have passed the array of employee list, now we will pass the dynamic list of users instead of a static array of the employee. Follow the below steps

Step 1:
Create the file src/components/manager/Manager.js if you have it already paste the below code snippet

import React from "react";
import './Manager.css'
import PropTypes from 'prop-types'

const manager = (props) => {
  return (
    <div>
      {props.isManagerLoggedin ?(
        <div>
          <h2>Welcome to your dashboard</h2>
          {props.employee.map(item => (
            <li key={item.name}> Name: {item.name}, ID: {item.id}, email: {item.email}</li>
          ))}
          <button onClick={props.logout}>Logout</button>
        </div>

      ) : (
          <div>
            <h2>Please login</h2>
            <button onClick={props.login}>Login</button>
          </div>
        )}
    </div>
  );
};

manager.propTypes = {
  isManagerLoggedin: PropTypes.bool,
  login: PropTypes.func,
  logout: PropTypes.func,
  employee: PropTypes.array
};

export default manager;

Step 2:
Create the file src/components/manager/Manager.css if you have it already paste the below code snippet

li{
    list-style: none;
    margin: 10px;
    padding: 10px;
    font-size: 22px;
}
input{
    list-style: none;
    margin: 10px;
    padding: 10px;
    font-size: 22px;
}
li {
    border: 1px solid black;
}

Step 3:
Create the file src/App.js if you have it already paste the below code snippet

import React, { Component } from 'react';
import './App.css';
import Manager from './components/manager/Manager';
import Container from './components/hoc/Container';
import axios from 'axios';
class App extends Component {
  constructor(props) {
    super(props);
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.state = { 
      isManagerLoggedin: false,
      employee: [
        {name:'Stark', empId:'123'},
        {name:'John', empId:'124'},
        {name:'Mickel', empId:'125'},
        {name:'Clark', empId:'126'}
      ]
    };
  }

  componentDidMount() {
    axios.get('https://jsonplaceholder.typicode.com/users').then(response => {
      console.log(response.data);
      this.setState({
        employee:response.data
      });
    });
  }

  login = e => {
    this.setState({ isManagerLoggedin: true });
  };

  logout = e => {
    this.setState({ isManagerLoggedin: false });
  };

  render() {
    return (
      <Container divClassName='App'>
        <h1>Welcome to react JS tutorial</h1>
        <Manager
          isManagerLoggedin={this.state.isManagerLoggedin}
          login={this.login}
          logout={this.logout}
          employee={this.state.employee}
        />
      </Container>
    );
  }
}

export default App;

Hit the URL: http://localhost:3000/, you can see the output which receives the user data from the API and then generated employee lists.

React http request example code snippet

One thought on “React http request example

Comments are closed.