jeudi 30 juillet 2020

Sending request to api using react

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 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZWViZGZiNTYwMjEwYTVmNTg4ZGJjZWQiLCJlbWFpbCI6ImRldmFubm5ubjtAdHlwLmluIiwiaWF0IjoxNTk2MDkzNDg1LCJleHAiOjE1OTYwOTcwODV9.7aTRvpyajCzbahrvq_nSIyppQpr2tWLAN_oKP2G0NeI

From response I need only: shopname,phoneNumber,address




Aucun commentaire:

Enregistrer un commentaire