I have a object like as follows
var obj={
userName:sessionStorage["userName"]
}
1st time if I try to access obj.userName i am getting undefined, because there is no value in it.
Now if I am getting undefined even after setting the value for it
sessionStorage["userName"]="name";
obj.userName; //undefined
How to solve this ?
userName takes the value of sessionStorage["userName"] at the time of its creation. Later changes to sessionStorage["userName"] will not be reflected in userName.
If you want to get sessionStorage["userName"] whenever you get value from userName, then you need to define a getter, like this
Object.defineProperties(obj, {
userName: {
get: function() {
return sessionStorage["userName"];
}
}
});
You should do this:
sessionStorage["userName"]="name";
obj.userName = sessionStorage["userName"];
obj.userName;//name
Just changing the value of sessionStorage doesn't reflect the change to the object itself.
In order to change the object, you need to actually change the object.
Related
In my functional component, I want to memorize some value which depends on Id property of an object:
obj={
innerProperty:{
id:1
}
}
useMemo(()=>someComplaxFunction(), [obj.innerProperty.id])
I want to do something like this, but the issue is, innerProperty can be undefined. So I need to add a check for innerProperty, but I cannot add that outside useMemo as it gives me error that hooks should not be called conditionally and not even inside as then I will have to add obj as dependency which I don't want because other properties may change.
Need to know how can I achieve this.
Any help is appreciated.
Thanks in advance!
obj={
innerProperty:{
id:1
}
}
const id = obj.innerProperty ? obj.innerProperty.id : undefined
// or using optional chaining(?.)
const id = obj.innerProperty?.id
useMemo(()=>someComplaxFunction(id), [id])
Inside your someComplaxFunction() check the value of innerProperty and return something like null so that you memorized value is null in this case (or anything else you want). And then use the memorized value in your component assuming that it could potentially be null.
Guess you shoud do some check. You can't do that logic inside ur dependecies array, but you can do something that way:
useMemo(()=> {
if (obj.innerProperty.id) {
someComplaxFunction()
}
}, [obj.innerProperty])
console.log(data)
{
"LoginDetails": "{\"BrowserInformation\":\"Mozilla\\/5.0 Chrome\\/76.0.1100.182 Safari\\/537.36\",\"ip_address\":\"180.80.21.172\"}"
}
from above object i want to take only the ip_address, i don't have idea how to get the value from above object
Use JSON.parse(obj)
var obj={
"LoginDetails": "{\"BrowserInformation\":\"Mozilla\\/5.0 Chrome\\/76.0.1100.182 Safari\\/537.36\",\"ip_address\":\"180.80.21.172\"}"
};
console.log(JSON.parse(obj.LoginDetails).ip_address)
Use JSON.parse(data.LoginDetails).ip_address. This will give the required value. For other parameters just need to change the name at last.
I am working with Javascript/ReactJS code, I am printing the Object(Obj), containing keys as ids and values as the status(true/false) of the corresponding keys in the console. The desired Object is printed, but as soon as I opened that object, it automatically changed its values.
the first property of this object is true, but when I open it, it goes false.
I declare that Object(Obj) outside the render method because it renders JSX every time either it needed or not. But it is not working.
render(){
return defaultApp(templates).map(template=>{
Obj[`${template._id}`] = false;
return <Apps id={template._id}
onClick={this.handleToggle.bind(this)}>
<h2>{template.title}</h2>
</Apps>
});
}
handleToggle = (e)=>{
var selectedAppId = e.target.id?e.target.id:e.target.parentNode.id;
if(!isEmpty(Obj)) {
Object.keys(Obj).forEach((id)=>{
if(selectedAppId===id){
Obj[selectedAppId] = !Obj[selectedAppId];
console.log(Obj);
this.setState({currentAppId:id,AppsStatus:Obj});
}});
}
I want to see the same Object's values either I open it or not.
console JSON.stringify(obj) to check the exact object values.
Remember objects are references so if their key values are changed at any point of the program, the change will be reflected all over the code as all the variables are storing the reference to that object.
I'm having trouble using the setter functions on my Sequelize js model properties.
What I want to do is when one property is given a value use that value to populate another property in the table at the same time.
In my model this is the code I have for the property in question...
date_time_paid: {
type:DataTypes.DATE,
set(val) {
const date = new Date(val);
this.setDataValue('date_time_paid', val); // set the the current property
this.setDataValue('month_paid', `${date.getFullYear()}-${(date.getMonth() + 1)}`); //also set another property on the same row
},
},
What I expect to happen is for the date_time_paid column to store the raw value and the month_paid column to store a string derived from it. But when I run my seeder to populate the table with test data the value for the month_paid column remains null.
Is this the correct use of a setter function?
If it is what have I done wrong that means it's not working?
I think you need a just a getter. Forget about date_time_paid and make getter for month_paid:
get month_paid(){
const date = new Date(this.date_time_paid);
return `${date.getFullYear()}-${(date.getMonth() + 1)}`;
}
I am creating a new Javascript object and passing the values into the constructor I would like the object to have. One value is a moment object (holding a date) I can see that the date is correct (2017-05-09) but the newly constructed object always has the value 2017-05-04. If I do a console.log on the attribute: object.start_date, then I am able to see the correct date, but if I do console.log on object, it shows the moment object with the wrong date 2017-05-04. I've tried updating in the constructor, manually doing an update on the object after creation, or by updating the value within the created object with a new instance function, but nothing changes the date. Here's some code/output.
Main question: Why is the moment object not being updating with the correct value I am giving it?
Thank you.
Function to create new route:
duplicateRouteSuccess(data) {
let route = new Route(data['routeData']);
route.changeStartDate(data['routeData']['starts_at']);
console.log(route);
console.log(route.starts_at);
this.routeCalendar.scheduleRoute(route, route.repeats);
this.close();
}
and the constructor:
constructor (data) {
this.id = data['id'];
this.name = data['name'];
this.starts_at = moment(data['starts_at']);
this.repeats = data['repeats'];
this.repeat_rate = data['repeat_rate'];
}
UPDATE
doing JSON.stringify to my objects did show that they both have the same date, of 2017-05-08. But then my question is "when I access the attribute object.start_date to set the object onto a calendar, why does object.start_date say 2017-05-04"? Here is the stringify output image:
UPDATE 2
The route.changeStartDate was just an instance function I created to attempt to update the "starts_at" field a second time since it did not appear to be updated in the constructor of the Route class. Here's the code for that:
changeStartDate(start_date){
this.starts_at = moment(start_date)
}