REACT fetch properties from nested JSON - javascript

I am using react to render data from properties in a json that is nested. I don't have a problem rendering the properties that are not nested such as 'name', and 'id', but when it comes to grabbing a nested prop such as place:location{...} etc, it says "TypeError: Cannot read property 'location' of undefined"
My json format looks as follows:
data = [ {
"end_time": "2015-03-28T21:00:00-0700",
"name": "Brkn Intl. Bay Area Season 2!",
"place": {
"name": "MVMNT Studio",
"location": {
"city": "Berkeley",
"country": "United States",
"latitude": 37.85381,
"longitude": -122.27875,
"state": "CA",
"street": "2973 Sacramento St",
"zip": "94702"
},
"id": "459771574082879"
},
"start_time": "2015-03-28T15:00:00-0700" }, ...]
This is my react code:
class ResultBox extends Component {
constructor(props){
super(props);
this.state = {
posts: []
};
}
componentDidMount() {
axios.get('http://localhost:3001/api/events')
.then(res => {
let posts = res.data.map(obj => obj);
this.setState({posts});
console.log(posts);
});
}
render() {
return (
this.state.posts.map(function(events){
return <div className='result_box'>
<p>{events.name}</p>
<p>{events.place.location.city}</p> <----- This give me error!!!
</div>
})
);
}
}
Any help would be appreciated!!!!

It looks like not all events have property place defined.
You can either warn about it on every component or just ignore and prevent undefined values to be rendered:
this.state.posts.map(events =>
<div key={events.id} className='result_box'>
<p>{events.name}</p>
{events.place && <p>{events.place.location.city}</p>}
</div>
)
Lodash's get method also can help you with this:
<p>{get(events, 'place.location.city', '')}</p>

Related

How can I get an array within a request response object in javascript/react?

How can I get the 'address' array within of request response object below?
{
"title": "MRS.",
"name": "Aluno",
"lastName": "3",
"birthday": "2019-08-31",
"address": [
{
"addressName": "rua 2",
"zipCode": "13901264",
"city": "amparo",
"state": "sp",
"country": "brasil"
},
{
"addressName": "rua 2",
"zipCode": "13901264",
"city": "amparo",
"state": "sp",
"country": "brasil"
},
]
}
If I save this object in a state called customer and print console.log(customer.address) it works well and I can see the address informations, but I can't use map or forEach methods like customer.address.forEach, I receive an error :(
You can use methods such as map, reduce, filter, forEach only on Array Not on Object.
the key address has value as an object, To read it you can simply use
console.log(customer.address.addressName) //street x
console.log(customer.address.zipCode) //13901264
If you want to loop through properties
Object.values(customer.address).forEach((value) => {
console.log(value);
})
// OR
Object.keys(customer.address).forEach((key) => {
console.log(customer.address[key]);
})
The property address it not an array, if you need to convert it into an array of one element you can use:
const valueAsArray = [response.address]
Object.keys(out.address).map(key => {
console.log(out.address[key]);
// etc ...
})

React cannot map through prop array

I fetch an api on componentDIdMount() then store the json to a state then I pass that state as a prop, I have no problem showing the data except on arrays.
<Component details={this.state.details} />
json:
{
"adult": false,
"backdrop_path": "/qonBhlm0UjuKX2sH7e73pnG0454.jpg",
"belongs_to_collection": null,
"budget": 90000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 878,
"name": "Science Fiction"
},
{
"id": 35,
"name": "Comedy"
},
{
"id": 10751,
"name": "Family"
}
]
}
then I try to map the genres:
<div className={style.genre}>
{details.genres.map(g => (
<span key={g.id}>{g.name}</span>
))}
</div>
But then I get Cannot read property 'map' of undefined, I don't know why this is happening because I'm able to do details.budget
It's trying to read data before you get the result from api.
so write the map function as
{details&&details.genres&&details.genres.map(g => (
<span key={g.id}>{g.name}</span>
))}
In react Initially when component is mounted, render() function is called and then componenentDidMount() is called in which you fetch data. So Initially details is empty. So you need to write the condition.

ReactJS set state does not assign array from Axios response data

I've defined an empty array in the react component constructor which I wish to assign with json response data from an API call
class Grid extends Component {
constructor(props) {
super(props);
this.state = {
blogs : []
};
}
I call the componentDidMount method to load data on this component where I'm using setState to assign values
componentDidMount(){
Axios.get("/api/blogs").then(response => {
const blogData = response.data;
this.setState({blogs: blogData.data});
});
}
The JSON response data is as follows (Laravel collection resource with meta and links)
{
"data": [
{
"title": "Experiments in DataOps",
"status": true,
"publish_date": "2020-01-29",
"slug": "experiments-in-dataops"
},
{
"title": "What is it about certifications anyway?",
"status": true,
"publish_date": "2020-01-29",
"slug": "what-is-it-about-certifications-anyway"
}
],
"links": {
"self": "link-value",
"first": "http://adminpanel.test/api/blogs?page=1",
"last": "http://adminpanel.test/api/blogs?page=1",
"prev": null,
"next": null
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "http://adminpanel.test/api/blogs",
"per_page": 15,
"to": 2,
"total": 2
}
}
the blogs array however remains undefined when I'm calling it later in populating the grid data
<BootstrapTable data={this.blogs} version="4" striped hover pagination search options={this.options}>
I get an empty table, calling console.log on blogs and this.blogs reveals it's undefined.
I'm using reactstrap and react-bootstrap-table for this grid component.
You are not accessing the state correctly to access the blogs use this.state.blogs:
<BootstrapTable data={this.state.blogs} version="4" striped hover pagination search options={this.options}>

displaying nested JSON with react js

I have an object like:
export const contact = {
_id: "1",
first:"John",
name: {
first:"John",
last:"Doe"
},
phone:"555",
email:"john#gmail.com"
};
I am reading it like
return (
<div>
<h1>List of Contact</h1>
<h1>{this.props.contact._id}</h1>
</div>
)
in this scenario I am getting expected output.
return (
<div>
<h1>List of Contact</h1>
<h1>{this.props.contact.name.first}</h1>
</div>
)
But when I read the nested property I am getting error like
Uncaught TypeError: Cannot read property 'first' of undefined
How to read these king of nested objects in react? Here is my source
Three things you need to address here:
this is your contacts-data and i don't see any first property within the name object:
export const contacts = {
"name": "mkyong",
"age": 30,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [{
"type": "home",
"number": "111 111-1111"
}, {
"type": "fax",
"number": "222 222-2222"
}]
};
You are calling this.props.fetchContacts(); on componentDidMount, hence in the first render call the state is still empty, the action call and the reducer will pass new props or change the state then you get to the second render call and that's the moment you have the data ready for use.
So you should check for the existing of the data before you try to use it. one way is to just conditionally render it (of course there are better ways to do it, this is just to make a point):
render() {
const { contacts } = this.props;
return (
<div>
<h1>List of Contacts</h1>
<h2>{contacts && contacts.name && contacts.name.first
//still getting error. "this.props.contacts.name" alone works
}</h2>
<h2>{contacts && contacts.address && contacts.address.city}</h2>
</div>
)
}
You are trying to use this.props.contact.name.first is that a typo? shouldnt it be contacts instead of contact?
EDIT:
As a followup for your comment, as a general rule in JavaScript (or any other language for that manner) you should always check the existence reference of an object before you are trying to access it's properties.
As for your use case you can use defaultProps if you must have a value to render or you can even simplify the scheme of your data.
This is much simpler to manage:
export const contacts =
{
"fName": "mkyong",
"lName": "lasty",
"age": 30,
"streetAddress": "88 8nd Street",
"city": "New York",
"homeNumber": "111 111-1111",
"faxNumber": "222 222-2222"
};
Than this:
export const contacts =
{"name": "mkyong",
"age": 30,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
};

Access nested Immutable Map property

I'm learning Immutable.js. I have an object that when called:
myObj.get('people')
returns the following:
[
{
"name": "John Stevenson",
"country": "Sweden"
},
{
"name": "John Silva",
"country": "Colombia"
},
{
"name": "John Van der Bier",
"country": "Holland"
},
{
"name": "John McDonald",
"country": "Scotland"
}
]
I'm trying to get inside this object so I can only see country:
myObj.getIn(['people', 'country']) // undefined
What am I missing?
The problem with you're code is that the result of getIn(['people', 'country']) is attempting to access the country property of people, which is an array and doesn't have a property named country. It seems like want to loop over people and build an array of their countries, which you can do with map:
var countries = myObj.get('people').map(person => {
return person.country
})
The previous answer will return an array. If you are truly wanting to use Immutable you should use
import { fromJS } from 'Immutable';
const immutableObj = fromJS(myObj);
//map() or forEach() here
var countries = immutableObj.map(person => {
return person.get('country');
})

Categories

Resources