Hi Team
I have code that fetch rest api, but i usually get this annoying syntax unexpected token < json position and data is not displaying and using localhost as json.
What I have tried:
// json file
<pre>{
"product_name": [
{
"id": 1,
"title": "2021 hot selling GPS 5G quadcopter drone with camera remote control aircraft drone WiFi mini drone camera"
}
],
"shipping_information": [
{
"id": 2,
"country": "South Africa",
"title": "Express UPS Saver (HK)",
"lead_time": "Lead Time 10 days",
"shipping_time": "Shipping Time 6 -10 days"
}
],
"options":[
{
"id":3,
"label":"1080p",
"price": 833.99,
"currency":"ZAR",
"symbol":"R"
},
{
"id":4,
"label":"4k",
"price":895.31,
"currency":"ZAR",
"symbol":"R"
},
{
"id":5,
"label": "Battery (Accessories)",
"price":78.5,
"currency":"ZAR",
"symbol":"R"
}
],
"discounts":[
{
"id":6,
"amount":"20%",
"end_date": "2022-06-18T03:11:46+02:00"
}
],
"reviews": {
"id": 7,
"rating": "5.0",
"count": 6,
"total_buyers": 18
}
}
// sidebar.js(fetching data using localhost as rest api)
import React,{ useEffect, useState} from 'react';
import './api/vaimo_db.json'
<pre lang="Javascript">class Sidebar extends React.Component {
state = {
isLoading: true,
prodData: [],
error: null
};
getFetchData() {
this.setState({ loading: true }, () => {
fetch("http://localhost:3000/shipping_information")
.then(res => res.json())
.then(result =>
this.setState({
loading: false,
prodData: result
})
)
.catch(console.log);
});
}
componentDidMount() {
this.getFetchData();
}
render() {
const { prodData, error } = this.state;
return (
<React.Fragment>
<h1>Fetching Data</h1>
{error ? <p>{error.message}</p> : null}
{
prodData.map(prod => {
const { id, country, title, lead_time, shipping_time } = prod;
return (
<div key={id}>
<p>{country}</p>
<p>{title}</p>
<p>{lead_time}</p>
<p>{shipping_time}</p>
<hr />
</div>
);
})
}
</React.Fragment>
);
}
}
export default Sidebar