I'm developing a webApp using React, I'm having issues accessing data inside a javascript Object, here is the code:
const user_position = System.prototype.getUserPosition();
console.log({user_position:user_position,latitude:user_position.latitude,longitude:user_position["longitude"]})
position_update.latitude = user_position.latitude;
position_update.longitude = user_position.longitude;
position_update.timestamp = user_position.timestamp
this.setState({currentSearchSelection: "La tua posizione"});
I want to access the data inside the user_position Object, but the output is quite strange:
{user_position: {…}, latitude: undefined, longitude: undefined}
latitude: undefined
longitude: undefined
user_position:
latitude: 41.818550699999996
longitude: 12.495401099999999
timestamp: 1587660938111
__proto__: Object
__proto__: Object
Basically, the user_position is populated but I cannot access the values inside it, what I'm doing wrong?
If you know the name of the exact values in the object, you can get it directly:
console.log(user_position.object_name)
Right now it is saying that your user_position is an object, and is defined.
Maybe even try just print that user_object
console.log(user_object) to see what is in it.
Thanks everybody for the support, the answer was simple: the getUserPosition() method was async(even it was not marked as it), so there was nothing wrong in the code of this particular class, what happened was:
user_position.object_name // print undefined since user_position is not populated
user_position // print value because the variable is linked to the result of the async method
So what I did was editing the code with a callback:
System.prototype.getUserPosition().then(user_position=>{
position_update.latitude = user_position.latitude;
position_update.longitude = user_position.longitude;
position_update.timestamp = user_position.timestamp
this.setState({currentSearchSelection: "La tua posizione"});
})
and everything worked.
Related
I am using the Ionic Framework for an app I am creating and got stopped by this. I'm using the Geolocation module to get the user's current position. I have an object that stores the latitude and longitude as so:
location_coordinate: {
latitude: number;
longitude: number;
}
But when I try to save the latitude and longitude to my object (this.location_coordinate.latitude = resp.coords.latitude;) this doesn't work and an error is thrown.
Error getting location TypeError: Cannot set property 'latitude' of undefined
If I set it to a variable, for example:
latitude: number;
And then:
this.lat = resp.coords.latitude;
This works. Why is this so? Am I missing something?
Note: The resp.coords.latitude is what is returned from the get request.
Error getting location TypeError: Cannot set property 'latitude' of undefined.
This error probably means location_coordinate is undefined. Check the code where you have defined [or maybe never defined?] this.location_coordinate. Once this is set to some object, you should definitely be able to use this.location_coordinate.latitude = resp.coords.latitude;
In order to validate my hypothesis, you can do following:
Assign a constant instead to see if error persists: this.location_coordinate.latitude = 0;
Print the value of this.location_coordinate before accessing this.location_coordinate.latitude
I'm aware that there are a lot of questions asking the same thing but none of those answers seem to work for my specific case and I have been at this for hours and still can't figure it out. I'm following a ReactJs tutorial for a WeatherApp.I get back an object from an API call that looks like this:
{
current: {}
forecast:
forecastday:[ //
0: {...}
1: {...}
2: {...}
3: {...}
4: {...}
] //Array of five objects
location: {}
} //this object is part of a bigger response object
When I console.log(objectName.forecast.forecastday) I get back the array, which means it's actually there.
But when I try
var forecastData = props.forecast.data;
var days = forecastData.forecast.forecastday.map(function (day) {
//do something
});
it gives me back the error Uncaught TypeError: Cannot read property 'forecast' of undefined. I have also tried logging forecastData and it comes back just fine. forecast is clearly there so unless I'm missing something extremely obvious, I don't know what's going on.
Thanks.
You are most likely not taking into account the initial state, where props.forecast.data may be undefined at the initial mount of the component since your API call is happening asynchronously.
You can do something like this:
var days = forecastData
? forecastData.forecast.forecastday.map(function (day) {
//do something
})
: null;
This will first check to see if forecastData exists, and if it does exist, it will map over the forecastData.forecast.forecastday array.
If forecastData does not exist, then that variable will render null.
The title might not be the best way to describe the problem, but I was wondering if there was a better practice to declaring an object in getDefaultProps?
In my render method I call several keys from from a prop/state that get updated on a click event i.e. this.props.player.name. The problem is that on page load this.props.player is blank and calling .name errors out. I know I can do something like ...
getDefaultProps: function() {
return {
player: {
name: null,
team: null
position: null
}
};
}
but it doesn't feel right. I was hoping there might be something similar to how Ruby does .try() where it won't try to call a method on a undefined prop.
The problem is specifically that this.props.player is undefined, if you define an empty object it will prevent the error from occurring. It's not bad practice to stub out the keys you're anticipating, but setting the default value to {} will be enough to prevent it from throwing.
You can create your data from ImmutableJS. Then you can get any part of your data like this:
this.state.getIn(['player', 'name', ...])
or
this.state.get('player')
This will not throw error even player is not defined or other, it will return undefined (or null) I don't remember
The update and updateIn work the same
see the doc here
I'd like to add this vanilla JS solution too - var x = (user || {}).name;
Source
I have this object called 'ctx.instance' which has the following properties:
firstName: 'Ron',
lastName: 'Santo',
minor: true,
accepted: false,
emailChanged: false,
organizationId: 000000000000000001000001,
isDeleted: false,
userId: 55e17a46e410f9603cea515b
This object was passed into my function. I need to strip off the 'emailChanged' property before saving it to the database. So I did this:
delete ctx.instance.emailChanged;
The delete returns 'true' which means the property doesn't exist.
The following statement after the delete yields false which also means it should be gone:
'emailChanged' in ctx.instance
Yet, if I do a console.log(ctx.instance), the 'emailChanged' property is still there and it gets saved to the database.
If I check the property's properties, it says it is configurable. If I do a console.log(ctx.instance.emailChanged) after the delete statement, it says 'undefined'.
Why is it still there?
I've searched all over the internet, tried tons of different things, and I can't find why this is occurring. This is happening within a Node environment.
UPDATE:
The DB is Mongo. I'm using Loopback.js models and framework.
The data variable is the object submitted to the server from the client via a PUT. The data object was originally JSON but Loopback has made it a JavaScript object.
The code is within an operation hook so the save to the DB doesn't live within this function.
The 'delete' statement is the last statement within the function before I pass it back off to the framework.
Here is the minimum code for the hook:
module.exports = function( Member )
{
Member.observe( 'before save', upsertMember );
function upsertMember( ctx, next )
{
// displays 'true'
console.log( ctx.instance.hasOwnProperty( 'emailChanged' ) );
// displays 'false'
console.log( ctx.instance.emailChanged );
var isDeleted = delete ctx.instance.emailChanged;
// displays 'true'
console.log( isDeleted );
// displays 'false'
console.log( 'emailChanged' in ctx.instance );
// displays 'false'
console.log( ctx.instance.hasOwnProperty( 'emailChanged' ) );
// displays 'undefined'
console.log( ctx.instance.emailChanged );
// displays object properties including 'emailChanged'
console.log( ctx.instance );
// pass control back to loopback for upsert
// 'emailChanged' gets into MongoDB record
next();
}
}
If any of you know a JSFiddle type of environment that includes Loopback, I'll throw it in there.
Screenshot of my debugger watch right after the delete statement:
According to Loopback Operation Hooks
Removing unneeded properties
To remove unwanted properties (fields) from the context object, use the following:
ctx.instance.unsetAttribute('unwantedField');
This completely removes the field and prevents inserting spurious data into the database.
Should have done this:
ctx.instance.unsetAttribute('emailChanged');
Could it be due to the PUT verb which is used to replace the whole instance and not only some attributes ?(To change only certain attributes you should use the PATCH verb).
So it might be loopback filling the missing attribute in the model and providing a default boolean value (false) for the "emailChanged" attribute.
I was able to remove the unnecessary property from being saved to dataabse using follwing statement Loopback version 3.
In case of ctx.data
delete ctx.data['propertyToBeRemoved'];
In case of ctx.instance
ctx.instance.unsetAttribute('propertyToBeRemoved')
Hope this works
data.emailChanged = undefined;
data.save(callback);
The questioner wants to delete the property of a model and save it to database. But the property of a model cannot be deleted using delete.
I asked a question yesterday, but I've kept going with it. Instead of calling next() and passing an an Error object, I worked out what it was doing, and tried to copy it. Now, when someone logs in and it fails, I do this:
res.render("pages/home",
{
flash:{"danger":["Login failed. Please enter your details and try again."]},
body:{},
section:"home",
locals : { userId : req.body.email }
}
This does exactly the same thing as the old code. I step through it, and I can see that the locals object contains a property called userId, with the value I expect. In the Jade template, I have this:
p it's #{typeof(userId)}
if(typeof(userId) != 'undefined')
p Welcome #{userId}
input(type='text', name='email', id="inputEmail", placeholder="Email", value="#{userId}")
else
input(type='text', name='email', id="inputEmail", placeholder="Email", value="")
This always renders as 'it's undefined' and then an empty text box. I have read several questions on this, and as far as I can see, they all say the same thing: if I set locals to be a JSON object, I can access it's properties by this syntax, but it does not work.
What am I doing wrong ?
You might first need to better understand how locals object actually work.
On the server-side, doing this:
res.render('view', { property: 'value' } );
would make property available in your views like so:
div Value = #{property}
You can also do the following to have the same effect:
res.locals.property = 'value';
res.render('views');
Note the usage of locals object. More info
Coming back to your issue, since you have
res.render("pages/home", { locals: { userId : req.body.email } })
to access userId in this case you would do:
p Welcome #{locals.userId}
So I'm guess you're confusing the two approaches ending up using locals object the wrong way.
OK - turns out that 'locals' doesn't mean anything any more. Leaving my code as it is, I needed to access 'locals.userId', but I could have just set the value of 'userId' and not had the 'locals' object at all.