Object is successfully passed as props but individual properties are 'undefined' - reactjs

so I am passing an object from my App component to a child component.
Within the render method I am able to see the value of my object by using console.log as so
this.props.data.documents[0]
I am able to see the key value pairs of the object contained at documents[0],
but when I try to single out the individual properties (like below) I get an undefined error.
this.props.data.documents[0].username
This is what console.log(this.props.data.documents[0]) prints
{user_id: "5dfd9f8afc5bdf1bef11b78c", username: "christine", name: "second", src: "../images/5dfd9f8afc5bdf1bef11b78c_second.png"}
user_id: "5dfd9f8afc5bdf1bef11b78c"
username: "christine"
name: "second"
src: "../images/5dfd9f8afc5bdf1bef11b78c_second.png"
And here is the error for console.log(this.props.data.documents[0].src
react-dom.development.js:25206 Uncaught TypeError: Cannot read property 'src' of undefined
Why could this be? Thanks in advance.

Related

Reactjs # symbol in parameter: item.enclosure.#attributes how to fix, that this is possible?

I have a .map function in my code and Im getting data from a json output but one of the item parameters is: #attribute but I cant have an # symbol in the parameter so is there any way I can fix this?
I coudn't really find anything about this because I'm not sure what to search for except for # symbol in parameter.
this is the code I used to get the data:
this.state.news.channel.item.map(function (item, i) {
console.log(item.enclosure.#attributes)
{#attributes: {…}}
#attributes:
length: "0"
type: "image/jpeg"
url: "https://media.nu.nl/m/aoqxps0aijuy_sqr256.jpg/barnier-eu-niet-onder-de-indruk-van-no-deal-brexit-dreigement.jpg"
__proto__: Object
__proto__: Object
So how can I fix that I can have an # in the parameter and it properly gets the data from the json.
Try this:
this.state.news.channel.item.map(function (item, i) {
console.log(item.enclosure["#attributes"])
});
Retrieving the value of a property
We can retrieve the value of a property using 2 different syntaxes.
const car = {
brand: {
name: 'Ford'
},
color: 'blue',
'the color': 'blue'
}
The first is dot notation:
car.color
The second, which is mandatory for properties with invalid names, is to use square brackets:
car['the color']
or even mixing:
car.brand['name']
car['brand'].name

React - shape method

I am going through some React code while I am learning it. I have come across the shape method used in PropTypes, as I understood we use the shape method to validate if the given value is of certain shape, that we pass it as an argument. But, not sure what is it's purpose if we don't pass it any value that we want to validate, like in this example:
Field.propTypes = {
fields: PropTypes.shape().isRequired,
};
Can't we just have it like this:
Field.propTypes = {
fields: PropTypes.isRequired,
};
PropTypes is not for production usage it's used in the development environment and it's not the replacement of validation as some newbie people get it wrong.
For example, I had this dropdown component.
Dropdown.propTypes = {
// Notice this I define the shape of object here
item: PropTypes.shape({
value: PropTypes.string,
text: PropTypes.string,
}),
};
Developers who are supposed to use this component they are required to pass item object but the problem is this component will only work when the object has the particular shape like this.
{
value: "value1",
text: "text1",
},
So, what I did I defined the shape of the object that how item's object should be and if a someone pass wrong shaped object the component will throw the warning in console.

React PropTypes - How to make a shape optional with its fields required?

I have a component that receives a badge prop (see example down below). The badge is optional, but once it is used I want it to have some required fields inside it. I've tried the following:
Component.propTypes = {
badge: PropTypes.shape({
src: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
}),
}
It works, but I get this warning on Chrome when trying to use it without the badge:
Warning: Failed prop type: The prop badge.src is marked as required
in Component, but its value is null.
What is the proper way of doing this?
Component usage example:
badge={{ src: 'usa.png', alt: 'United States' }}
badge not supplied
This is the correct way to do this. I was very intrigued by how this wouldn't work, so I pasted it in a CodePen (https://codepen.io/Oblosys/pen/xLvxrd) and it works just as expected. (Open a console, and uncomment the failing one to see a prop-type error)
Something else must be going wrong in your code, and at some point you render a Component with a badge property object that has src: null. Maybe before data from an api request has arrived? With some console logging in Component and its parent, you should be able to find the culprit.

Restangular - How do I reach this API using GET method?

How do I make a GET call to a REST API with the below signature:
http://www.example.com/hierarchies/nodes/1005/parents
I am trying to call the API like so:
var service = Restangular.all('hierarchies');
return service.one('nodes', id).all('parents').get();
But it throws the following error:
TypeError: Cannot read property 'toString' of undefined
The API call(if successful) would respond in a nested format as below:
{
name: "",
children: [
{
name: "",
children: [
{
name: "",
children: [
..
]
}
]
}
]
}
Thanks in advance!
I think if you use all as the last part of the builder, a list is expected and you should use getList instead of get. However the object you are expecting does not look like a list, so you could change the last part of your builder to just use one without the second parameter and then a single object as the response will be expected.
service.one('nodes', 5).one('parents').get().then(function(response) {
});

get not retrieving name attribute from object

From the backbone docs
getmodel.get(attribute)
Get the current value of an attribute from the model. For example: note.get("title")
I seeded some data with a name for each country into a Rails app
Country.create!(name: "Brazil")
Country.create!(name: "France")
Country.create!(name: "Germany")
Country.create!(name: "Spain")
In the console, I created a new collection and fetched the data
countries.fetch();
Object
XHR finished loading: "http://localhost:3000/countries".
Checked the length. Equal to the four countries I created.
countries.length
4
Selected a random one using underscore's shuffle method.
c = countries.shuffle()[0]
The object has a name
Backbone.Model
_changes: Array[2]
_currentAttributes: Object
_events: Object
_hasComputed: false
_previousAttributes: Object
attributes: Object
country: Object
created_at: "2013-01-07T06:09:43Z"
id: 2
name: "France"
updated_at: "2013-01-07T06:09:43Z"
__proto__: Object
__proto__: Object
Tried to get the name attribute from the object several different ways, all without success
c.get('name')
undefined
c.get("name");
undefined
c.get("name")
undefined
Can anyone think what I might be doing wrong?
One thing that I find unusual is that there is a 'country' attribute wrapping the other attributes
attributes: Object
country: Object
created_at: "2013-01-07T06:09:43Z"
id: 2
name: "France"
updated_at: "2013-01-07T06:09:43Z"
I'm not sure why 'country' is wrapping the other data. Is it because I created the seed data with a Country model?
Country.create!(name: "Brazil")
anyways, obj.get('country') doesn't return undefined
c = countries.shuffle()[0]
k = c.get('country')
Object
created_at: "2013-01-07T06:09:43Z"
id: 3
name: "Germany"
updated_at: "2013-01-07T06:09:43Z"
__proto__: Object
but I can't do a get on the name after that (i.e after I did the get on country)
k = c.get('country')
Object
k.get('name')
undefined
Is there a way to remove the country wrapper and just be able to do get on the attributes that it was created with?
Override model.parse to extract the country element. Backbone calls parse before populating the model from fetched data:
var Country = Backbone.Model.extend({
parse: function(attributes) {
return attributes.country;
}
});

Resources