Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reading JSON response from an API [array] [Array of objects] [Axios]
import React, { Component } from 'react';
import styled from 'styled-components'
import axios from 'axios';
import { toaster, Spinner, Pane, Alert } from 'evergreen-ui'
import { Link } from 'react-router-dom';
import TopHeader from '../TopHeader/TopHeader';
const PromoCard = styled.div`
box-shadow: 0px 4px 26px rgba(0, 0, 0, 0.24);
border-radius: 10px;
overflow:hidden;
`
const PromoCardSingle = styled.div`
padding:0 0 10px 0;
`
const PromoCardSingleTitle = styled.div`
font-size:16px;
padding:10px 0 0 15px;
font-weight:500;
`
const PromoCardSingleSubTitle = styled.div`
font-size:14px;
padding:0 0 0 15px;
color: #757575;
`
class Home extends Component {
constructor(props) {
super(props);
this.state = {
// "promo": [
// {
// "id": "1",
// "vendor_id": "1",
// "promo_code": "eats-tanvira980ue",
// "description": "For first time user.",
// "vendor_name": "Uber Eats",
// "vendor_image": "https://upload.wikimedia.org/wikipedia/commons/2/23/Uber_eats_logo_2017_06_22.jpg",
// "vendor_tagline": "best foods"
// }
// ],
'promo': [],
'dataLoaded': false,
'showDetails': false,
'isServerError':''
}
}
componentDidMount() {
var bodyFormData = new FormData();
bodyFormData.append("FORM_DATA_NAME", "FORM_DATA_VALUE");
var self=this;
axios({
method: 'post',
url: 'YOUR_API_ENDPOINT_HERE',
data: bodyFormData,
headers: { 'Content-Type': 'multipart/form-data' },
crossdomain: true
})
.then(res => {
this.setState({ promo: res.data, dataLoaded: true })
})
.catch(function (error) {
self.setState({ isServerError: true})
toaster.danger('Something went wrong',
{
id: 'loadIndicator',
description: '' + error
})
})
}
render() {
let promoview = (
<div className="row">
{this.state.promo.map((promo) => {
return (
<div className="col-6 col-md-4 col-lg-4 col-sm-6 mb-4" key={promo.id}>
<Link to={`/details/${promo.id}`}>
<PromoCard className="promo_card" >
<PromoCardSingle >
<img src={promo.vendor_image} alt="" width="100%" height="100%" />
<PromoCardSingleTitle>{promo.vendor_name}</PromoCardSingleTitle>
<PromoCardSingleSubTitle>{promo.vendor_tagline}</PromoCardSingleSubTitle>
</PromoCardSingle>
</PromoCard>
</Link>
</div>
)
})}
</div>
)
return (
<>
{this.state.isServerError ? <Alert intent="danger" title="Server may be down at this moment. Try again later"
/> : null}
<TopHeader pageTitle="All Promo & Discounts"/>
<div className="container mt-4">
{!this.state.dataLoaded ? <Pane display="flex" alignItems="center" justifyContent="center" height={400}>
<Spinner />
</Pane> : null}
{promoview}
</div>
</>
);
}
}
export default Home;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment