Async Storage retrieve value of key in item - javascript

I'm new to Javascript and react native, and the question itself will be probably very easy to answer.
I'm setting up a AsyncStorage and creating a Item inside the storage, which is a .JSON that has 3 key values to it.
const saveDataToStorage = (token, userId, expirationDate) => {
AsyncStorage.setItem('userData', JSON.stringify({
token: token,
userId: userId,
expiryDate: expirationDate.toISOString()
}))
};
What I want to do now is to retrieve the "userId" value from this item in an other part of the project but here is the problem.
var PersonalId = await AsyncStorage.getItem('userData');
console.log(PersonalId);
console.log(typeof PersonalId);
I know how to access the item itself, but I have no clue how to access the special key inside it. I can not use the command:
var PersonalId = await AsyncStorage.getItem('userData').userId;
because the item from the AsyncStorage is a string, I know this because I got this info from the second line of my code.
console.log(typeof PersonalId);
How can I access the special key "userId" inside my item "userData" and not the whole item itself? I cant work with the item anyways because its a string, I can not treat it as an object and thats my problem.
Thank you for reading and helping out!

You need to first parse value you are getting from the AsyncStorage into a JSON object using JSON.parse(). Try this implementation.
const get_data = async () => {
const userData = await AsyncStorage.getItem("userData");
const userObject = userData !== null ? JSON.parse(userData) : {};
const personalId = userObject.userId;
console.log(personalId);
};

You are forgetting that you stringified the JSON before saving it to storage.. so you are getting string when you read it. Simply JSON.parse the returned string and you should be on your way.
const userData = await AsyncStorage.getItem('userData');
const personalId = JSON.parse(userData).userId;
You should also wrap the above code in a try-catch to make sure you catch errors when invalid data is tried to be parsed and it throws an error.

Related

Logging object but not able to log the object keys

I have saved an object in Redis in this format
let redisObject = {
sessionID: this.data.sessionID,
forWardTime: new Date(),
};
I am calling the object and the data is being retrieved successfully
let redisData = await this.getDataFromRedis ....
And the weird part I am being able to log the Redis data example
console.log("redisData =>",redisData)
it is returing
redisData => {"sessionID":"OyMUuUgeimTeU3OfNWyDtgkGeHsniF","forWardTime":"2022-03-22T19:16:05.507Z"}
But
console.log(redisData.sessionID)
And
console.log(redisData.forWardTime)
are both returning undefined? What's the problem and what am I missing
Your getDataFromRedis() function isn't parsing the data, so you're logging the JSON string, not an object.
Change to:
let redisData = JSON.parse(await this.getDataFromRedis(...));

retrieving data from database according to query conditions

"_id":{"$id":"61b5eb36029b48135465e766"},
"name":"push-ups","link":"https://google.com",
"image":"https://google.com",
"gender":["0","1","2"],
"goal":["lw","gw","sf"],
"age":60,
"excersietype":"chest",
"__v":0
this is how my data is stored in database
and I want to fetch data according to 3 condition
I got 3 queries from front gender goal and age and according to that I have to retrieve data
const gender = req.query.gender;
const age = req.query.age;
const goal = req.query.goal
const level = req.query.level
if (level==='fb'){
const getdata = new Forbeg.find({gender:{$in:gender}},{age:{$lte:age}},{goal:{$in:goal}});
console.log(getdata)
}
Is this a good way to find the data because I am getting error
UnhandledPromiseRejectionWarning: MongooseError: `Model.find()` cannot run without a model as `this`. Make sure you are not calling `new Model.find()`
I am getting above error while fetching
The error is explicit : Make sure you are not calling 'new Model.find()'. Use const getdata = Forbeg.find(...).
However, you will immediately run into the next problem, as Mongoose models return thenables (Promise-like). console.log(getdata) will log Promise<pending>. You need to resolve your database call, either by doing
Forbeg.find(...).then( getdata => console.log(getData));
or (much more better!):
const getdata = await Forbeg.find(...);
console.log(getdata)
Even better, add .lean() to get simple JSON data instead of an array of Mongoose objects (faster), and .exec() to get a true Promise instead of a thenable :
const getdata = await Forbeg.find(...).lean().exec();
console.log(getdata)
Remove new operator
const getData = Forbeg.find({gender:{$in:gender}},{age:{$lte:age}},{goal:{$in:goal}});

How to crawling using Node.js

I can't believe that I'm asking an obvious question, but I still get the wrong in console log.
Console shows crawl like "[]" in the site, but I've checked at least 10 times for typos. Anyways, here's the javascript code.
I want to crawl in the site.
This is the kangnam.js file :
const axios = require('axios');
const cheerio = require('cheerio');
const log = console.log;
const getHTML = async () => {
try {
return await axios.get('https://web.kangnam.ac.kr', {
headers: {
Accept: 'text/html'
}
});
} catch (error) {
console.log(error);
}
};
getHTML()
.then(html => {
let ulList = [];
const $ = cheerio.load(html.data);
const $allNotices = $("ul.tab_listl div.list_txt");
$allNotices.each(function(idx, element) {
ulList[idx] = {
title : $(this).find("list_txt title").text(),
url : $(this).find("list_txt a").attr('href')
};
});
const data = ulList.filter(n => n.title);
return data;
}). then(res => log(res));
I've checked and revised at least 10 times
Yet, Js still throws this result :
root#goorm:/workspace/web_platform_test/myapp/kangnamCrawling(master)# node kangnam.js
[]
Mate, I think the issue is you're parsing it incorrectly.
$allNotices.each(function(idx, element) {
ulList[idx] = {
title : $(this).find("list_txt title").text(),
url : $(this).find("list_txt a").attr('href')
};
});
The data that you're trying to parse for is located within the first index of the $(this) array, which is really just storing a DOM Node. As to why the DOM stores Nodes this way, it's most likely due to efficiency and effectiveness. But all the data that you're looking for is contained within this Node object. However, the find() is superficial and only checks the indexes of an array for the conditions you supplied, which is a string search. The $(this) array only contains a Node, not a string, so when you you call .find() for a string, it will always return undefined.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
You need to first access the initial index and do property accessors on the Node. You also don't need to use $(this) since you're already given the same exact data with the element parameter. It's also more efficient to just use element since you've already been given the data you need to work with.
$allNotices.each(function(idx, element) {
ulList[idx] = {
title : element.children[0].attribs.title,
url : element.children[0].attribs.href
};
});
This should now populate your data array correctly. You should always analyze the data structures you're parsing for since that's the only way you can correctly parse them.
Anyways, I hope I solved your problem!

how to access json data os asyncStorage function

I am using AsyncStorage to store data. Here is my function of storing data :
const profile = { userId, name, email };
await AsyncStorage.setItem('userProf', JSON.stringify(profile));
I have a problem when I try to access the data , if I console.log:
async componentWillMount(){
const profile = await AsyncStorage.getItem('userProf');
console.log(profile);
}
{"userId":"jefla3E0tjcJHhHKJK45QoIinB2","name":"egfgege","email":"ergeg#egrge.com"}
Now if I am willing to get only email value , I have tried with:
console.log(profile.email);
console.log(profile[0].email);
None of them worked, I get undefined as output, could you please help.
As AsyncStorage take and returns a string you will need to parse the string into json. You're already using JSON.stringify to save your object, you need to do the reverse operation to get it back to being an object.
const savedProfile = await AsyncStorage.getItem('userProf');
const profile = JSON.parse(savedProfile);
Then you should be able to access it the properties as you normally would, for example
const userId = profile.userId;
const email = profile.email;
const name = profile.name;
You may want to make sure that you perform a check that the returned value from AsyncStorage isn't null, as that will cause problems for you. Also await functions can throw, so you should make sure that you wrap your call to AsyncStorage in a try/catch
async componentWillMount(){
try {
const savedProfile = await AsyncStorage.getItem('userProf');
// you should check that the savedProfile is not null here
const profile = JSON.parse(savedProfile);
const userId = profile.userId;
const email = profile.email;
const name = profile.name;
} catch (err) {
console.warn(err);
}
console.log(profile);
}
When storing the value with AsyncStorage.setItem( ... ), you use JSON.stringify to convert the complete object into a String. This means, if you want to have a "normal" Object back (to use the dot operator), you have to use JSON.parse:
const profile = await AsyncStorage.getItem('userProf');
console.log(JSON.parse(profile));

How to make toString function for multiple data?

I don't know why mongo mlab _id is not a string? I need to double check context and the viewer._id in my schema. This is my code:
resolve: async ({_id}, {status, ...args}, context) => {
// {_id} destructure _id property on root
console.log("allTodosByUser field = ",_id)
console.log("allTodosByUser field = ",context.user._id)
console.log("allTodosByUser equal",Boolean(_id.toString() === context.user._id.toString())) // suddenly using toString becomes true
This is not really a big deal but somehow I don't want to use toString for comparison:
if(_id.toString() === context.user._id.toString())
So I want to make a function maybe like this:
const { _id, context.user._id: contextUserId } = [_id, context.user._id], // push the _id, and context.user._id in an object so I can destructure?

Categories