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
There are a few changes required to make your code working:
this.state
in class constructor. This property will store data from API and be used during renderingcomponentDidMount
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.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.
Comments