Reputation: 184
I'm trying to create a MERN app while using Axios to send requests to the back end, but I can't get the data to render on the page.
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
export default class City extends Component {
constructor(props){
super(props);
this.state = {
selected_city: {
_id: "",
name: "",
country: ""
}
};
}
//Retrieves the requested city from the back-end to update the page's state.
componentDidMount(){
let city_name = this.props.match.params.name
axios.get('http://localhost:4000/city/' + city_name)
.then(response => {
console.log("Response: " + response);
console.log("Data: " + response.data);
console.log("String version: " + JSON.stringify(response.data));
console.log("Name: " + response.data.name);
this.setState({selected_city: response.data});
})
.catch(function(error){
console.log(error);
})
}
render() {
return (
<div className='text-center'>
<p>Name: {this.state.selected_city.name}</p>
<p>Description: {this.state.selected_city.country}</p>
</div>
)
}
}
The user is meant to enter the city name at the main landing page (e.g. London) and land on a page with a URL like localhost:3000/city/<city-name>
with just a couple of details about it.
The thing is, the data is showing up in the console like so:
Response: [object Object]
Data: [object Object]
String version: [{"_id":"5f5637ecf06f63e92b39e71d","name":"London","country":"United Kingdom"}]
If I query the endpoints using Postman, I also get the expected JSON response.
EDIT: I added a dummy variable in the Axios GET like so:
axios.get('http://localhost:4000/city/' + city_name)
.then(response => {
console.log("Response: " + response);
var dummy_city = {"_id": "1215144156", "name": "London", "country": "United Kingdom"};
this.setState({
selected_city._id: dummy_city._id,
selected_city.name: dummy_city.name,
selected_city.country: dummy_city.country
//this.setState({selected_city: response.data});
})
.catch(function(error){
console.log(error);
})
...and the dummy data shows up, but I've still got no luck accessing the data from the GET response. What am I doing wrong?
Upvotes: 0
Views: 602
Reputation: 237
For debugging purpose you should try to log the content of your state inside the render method. (E.g : console.log(this.state) under the render()).
This will help you understanding if you AT LEAST made it to the point where your state is updated. If not the problem is from the response from the axios, otherwise it's how you access your data.
My guess would be that the response from your API is an array, so this.state.selected_city must be an array. If so, accessing it like this.state.selected_city.name would do nothing
Upvotes: 1