I have a Node API that returns data in a JSON format and sends it to a React Component App
that stores it in its state (nearbyShops
) to pass it afterwards to the NearbyShop
component props. The thing is I don't get the content displayed even though I used componentDidMount
.
App.js
:
import React, { Component } from 'react';
import axios from 'axios';
import './App.css';
import NearbyShop from './NearbyShop';
class App extends Component {
constructor(props) {
super(props);
this.state = {
lat: 0,
long: 0,
nearbyShops: []
}
}
componentDidMount() {
var that = this;
// Get the user's location (lat & long) in the state object
const url = 'https://freegeoip.net/json/';
axios.get(url)
.then((response) => response.data)
// Get the long & lat of the end-user
.then((data) => that.setState({
lat: data.latitude,
long: data.longitude
}))
// Call our built-in Nearby API with the lat & long of the end-user
.then(function (data) {
axios.get('/nearby', {
params: {
lat: that.state.lat,
long: that.state.long
}
})
.then((response) => that.setState({
nearbyShops: response.data.nearbyShops
}))
.catch(function (error) {
console.log(error);
});
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<div className="App">
<h1>Shops List</h1>
<NearbyShop shopsList={this.state.nearbyShops} />
</div>
);
}
}
export default App;
NearbyShop.js
:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {
Card, Button, CardImg, CardTitle, CardText, CardGroup,
CardSubtitle, CardBody
} from 'reactstrap';
class NearbyShop extends React.Component {
constructor(props) {
super(props);
this.state = {
shopsList: props.shopsList
}
}
componentDidMount() {
const shopsList = this.props.shopsList;
this.setState({
shopsList: shopsList
});
}
render() {
if (this.state.shopsList.length == 0)
return null;
let shops = this.state.shopsList && this.state.shopsList.map(function (shop, i) {
<Card key={i}>
<CardImg top width="100%" src={shop.picture} alt="Card image cap" />
<CardBody>
<CardTitle>{shop.name}</CardTitle>
<CardSubtitle>Card subtitle</CardSubtitle>
<CardText>{shop.email}</CardText>
<Button>Fall in love</Button>
</CardBody>
</Card>
})
return (
<CardGroup>
{shops}
</CardGroup>
);
}
}
export default NearbyShop;