Sending request to api using react

Himanshu Bhardwaj

Hello I am New to React,and I don't know to to send request to an api using react and how to feed the response data to my component

shop.jsx

import React from 'react';
import './shop.css';

class Shop extends React.Component{
    render(){
        return(
            <div class="blog-post">
                <div class="blog-post_img">
                    <img src="shop.jpg" alt=""></img>
                </div>
                <div class="blog-post_info">
                    <h1 class="blog-post_title">{this.props.name}</h1>
                    <p class="blog-post_text">
                        {this.props.address}
                    </p>
                    <p class="blog-post_text">
                        {this.props.mobile}
                    </p>
                    <a href="#" class="blog-post_cta">Visit Shop</a>
    
                </div>
            </div>
        );
    }
}
export default Shop;

shops.jsx

import React from 'react';
import './shops.css';
import Shop from './shop'

class Shops extends React.Component{
    constructor() {
        super()
      }
      componentWillMount() {
        this.getData()
      }
      getData() {
        // create a new XMLHttpRequest
        var xhr = new XMLHttpRequest()
    
        // get a callback when the server responds
        xhr.addEventListener('load', () => {
          // update the state of the component with the result here
          console.log(xhr.responseText)
        })
        // open the request with the verb and the url
        xhr.open('GET','http://localhost:5000/api/shops/allShops')
        // send the request
        xhr.send()
      }
    render(){
        const shopjsx = this.state.shops.map((item, i) =>(<Shop name={item.shopname} address={item.address} mobile={item.phoneNumber}/>));
        return(
            <div id="container">
                {shopjsx}
            </div>
        );
    }
}
export default Shops;

I know that my code for shops.jsx is wrong, what I want is that, I want to make request to my api, and want that when I get the data from api, I need to put that data in shop.jsx components

Request to the api should be sent like this: GET http://localhost:5000/api/shops/allShops Authorization: Bearer dcbjdsbchjedjcvdfcvfcjdfvcjfdjcvfdjcjdfjchjdfchbdfcjhdfhcbj

From response I need only: shopname,phoneNumber,address

response from my api looks like this:

fetchedShops: Array(78)
0:
created_at: "2020-06-18T07:50:42.356Z"
isActive: true
isApproved: false
isOpen: true
isPhoneVerified: false
name: "kalluHalwai"
phoneNumber: "9829648597"
plans: []
timingRules: {lunchCancellationDeadline: 1030, dinnerCancellationDeadline: 1730}
updated_at: "2020-06-18T07:50:42.356Z"
__v: 0
_id: "5eeb1cd295c9523da0a99ee0"
__proto__: Object
1:
created_at: "2020-06-18T09:30:28.985Z"
isActive: true
isApproved: false
isOpen: true
isPhoneVerified: false
name: "kalluHalwai"
phoneNumber: "9829648597"
plans: []
timingRules: {lunchCancellationDeadline: 1030, dinnerCancellationDeadline: 1730}
updated_at: "2020-06-18T09:30:28.985Z"
__v: 0
_id: "5eeb3434e2662738509ebf8a"
__proto__: Object

macborowy

There are a few changes required to make your code working:

  • set up this.state in class constructor. This property will store data from API and be used during rendering
  • use componentDidMount instead of componentWillMount . The componentDidMount method runs after first render of the component. It is a good place to add requesting 3rd party for data.
  • use fetch to get the data from API instead of XMLHttpRequest. It makes code clearer and easier to use.

Here is working example:

class Shops extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      shops: []
    };
  }

  componentDidMount() {
    // replace with correct token and URL: http://localhost:5000/api/shops/allShops
    const TOKEN = "";
    fetch("https://jsonplaceholder.typicode.com/posts", {
      method: "get",
      headers: new Headers({
        Authorization: `Bearer ${TOKEN}`
      })
    })
      .then(response => response.status === 200 ? response.json() : [])
      .then(data => this.setState({ shops: data }))
      .catch(err => console.log("Error", err));
  }

  render() {
    const shops =
      this.state.shops.length > 0 ?
        this.state.shops.map(item => (
          <Shop name={item.id} address={item.title} mobile={item.body} />
        ))
        : <span>No data</span>;
    return <div id="container">{shops}</div>;
  }
}

class Shop extends React.Component {
  render() {
    return (
      <div class="blog-post">
        <div class="blog-post_img">
          <img src="shop.jpg" alt="" />
        </div>
        <div class="blog-post_info">
          <h1 class="blog-post_title">{this.props.name}</h1>
          <p class="blog-post_text">{this.props.address}</p>
          <p class="blog-post_text">{this.props.mobile}</p>
          <a href="https://google.com" class="blog-post_cta">
            Visit Shop
          </a>
        </div>
      </div>
    );
  }
}

ReactDOM.render(<Shops />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

It requests publicly available API so data is different and no token is required (I add setting the Authorization header, but it is not used by the API).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Sending POST request to API using Alamofire

Sending data from react to node by get request using axios library

Sending get request to an Laravel API using axios in Vue.js

(500) Internal Server Error - When sending web request using api

using dask for sending parallel API request and error handling

Sending a POST request to API with localhost

Alamofire sending a request to an API 'NSInvalidArgumentException'

Sending API request via Postman?

Django API request is empty using React

Using useEffect in React to change API request

Sending a multipart request using RestTemplate

Getting Internal Server Error when sending POST request with an image file to database using React JS and Laravel

Getting issue while sending nested JSON as request to validate the POST REST API method using Karate framework

React fetch sending request multiple times

React history.push sending page request?

Sending Headers with a GET request to Third Party API

Nodejs sending external API POST request

sending cookies with ajax request via fetch api

sending a post request to an external API and extracting data

Sending a JSON POST request to REST API in PHP

Rxswift validate inputs before sending api request

issue with sending headers in post request to the API

Error while sending a request to fluxpoint api

Sending Post Request to Open Elevation API

sending request to reCAPTCHA Enterprise API fails

How to send a POST request to Flask API using Fetch in a React app

Request to api works fine in component but not when using provider with react

Sending get request using python-requests

Using brackets in PowerShell when sending a request