Values are not stored in array AsyncStorage react native - arrays

I am trying to store values in AsyncStorage as array, but values are not saving there and getting nothing when i try to get the values from array.Any help would be appreciated.Thank you in advance,here is my code :
let searchString = this.state.inputValue
AsyncStorage.getItem('searches', (res) => {
var searches
if (res === null) {
searches = []
}else {
searches = JSON.parse(res)
}
searches.push({
searchString: searchString
})
AsyncStorage.setItem('searches', JSON.stringify(searches), (res) => {
console.log('====FirstPage====setItem==async==='+res)
})
});
//getting values from asyncstorage :
AsyncStorage.getItem('searches', (res) => {console.log('===res==='+res)})

Please try this
AsyncStorage.getItem("searches").then((value) => {
this.setState({"searches": value});
}).done();
Also see
https://www.thepolyglotdeveloper.com/2015/09/saving-data-in-your-react-native-mobile-application/

You can store the data as following:
AsyncStorage.setItem('searches', JSON.stringify(searchString));
In order to fetch/get, you can do that using following:
AsyncStorage.getItem('searches', (err, result) => { // err indicating the error
console.log("Storage Data(String):", result); // print is string format
console.log("Storage Data(Object):", JSON.parse(result)); // print is json format
})

Related

How to return this local variable in nested functions and "globalize" it?

I am trying to catch some values from a file and put them in an array.
After battling up with conversions and values, I reach my "final" data to return which in my case is arrayFile.I understand that I have nested some functions and now I couldn't return my data properly and globally in the first part of the code, because it displays/returned undefined.
In a few words,how I can retutn this variable specifically or in another variable? Because the console.log works, however just in that block. How could I end my 1st FOR loop and keep the data (arrayFile) global so for being used in other stuff? Any help wuold be precious. Hoping I'm asking questions the right way, thanks for your patience.
const directoryPath = path.join(__dirname, './sample');
//passing directoryPath and callback function
fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function (file) {
arrayNomi.push(file);
});
for(i=0;i<arrayNomi.length;i++){
leggiFile(arrayNomi[i],arrayDati)
}
});
function leggiFile(nomeFile,arrayFile){
const xmlFile = fs.readFile(nomeFile,{encoding:'utf8', flag:'r'},
function(err, data) {
if(err)
console.log(err);
else
convert.parseString(data, (err, result) => {
if(err) {
throw err;
}
// `result` is a JavaScript object
// convert it to a JSON string
//const json = JSON.stringify(result, null, 4);
//console.log(json)
// log JSON string
//console.log(json);
// method to collect string values
const collectAllValues = (arr, res = []) => {
// append result "res" with any "string" elt in array "arr"
const r = [
...res,
...(
arr?.filter(
elt => typeof elt !== 'object'
) ?? []
)
];
// filter out "arr" elements that are "objects"
const nx = arr?.filter(
elt => typeof elt === 'object'
) ?? [];
// if "objects" exist in "arr" elements-list
// use ".reduce()" to iterate over the filtered "arr"
// then, for each object, use ".reduce()" to
// iterate over values that are arrays and make
// recursive call to this method & return the value
if (nx && nx.length) {
return (
nx.reduce(
(acc, ob) => ([
...acc,
Object.values(ob)
.filter(v => v && Array.isArray(v))
.reduce((ac2, ar) => ([...ac2, ...collectAllValues(ar)]), acc)
.flat()
]),
r
)
);
} else return r;
// if no "objects" exist, simply return earlier
// result "r"
};
console.log(
'collect all values:\n',
Object.values(result["p:FatturaElettronica"])
.filter(v => v && Array.isArray(v))
.reduce((acc, ar) => ([...acc, ...collectAllValues(ar)]), [])
.flat()
);
var jsonDatiTabella = {};
var dati = [];
jsonDatiTabella.dati = dati;
var tipoDocumento= result["p:FatturaElettronica"].FatturaElettronicaBody[0].DatiGenerali[0].DatiGeneraliDocumento[0].TipoDocumento[0];
var dataDocumento= result["p:FatturaElettronica"].FatturaElettronicaBody[0].DatiGenerali[0].DatiGeneraliDocumento[0].Data[0];
var importo = result["p:FatturaElettronica"].FatturaElettronicaBody[0].DatiGenerali[0].DatiGeneraliDocumento[0].ImportoTotaleDocumento[0];
var prestatore= result["p:FatturaElettronica"].FatturaElettronicaHeader[0].CedentePrestatore[0].DatiAnagrafici[0].Anagrafica[0].Denominazione[0];
var committente= result["p:FatturaElettronica"].FatturaElettronicaHeader[0].CessionarioCommittente[0].DatiAnagrafici[0].Anagrafica[0].Nome[0];
var tempDati = {
"TipoDoc": tipoDocumento,
"DataDoc": dataDocumento,
"Importo":importo,
"CedentePrestatore" :prestatore,
"CessionarioCommittente":committente
}
jsonDatiTabella.dati.push(tempDati);
console.log(jsonDatiTabella);
arrayFile.push(tempDati.TipoDoc,tempDati.DataDoc,tempDati.Importo,tempDati.CedentePrestatore,tempDati.CessionarioCommittente)
console.log("arrayFile:" + arrayFile)
});
});
}

how to detect that return value from api is an empty object - angularjs call api

this is my code:
getSetting() {
Loading.show();
const data = {
vendorId: JSON.parse(localStorage.getItem("TOKEN_DATA_MAGIC")).user
.vendorId,
};
this.api.getSetting(data).subscribe(
(data) => {
console.log(data);
let res: any = data;
if (res.setting != "not found") {
const res: any = data;
this.settingItem.Selling_Type = res.setting
? res.setting.Selling_Type
: null;
this.settingItem.Closing_hours = res.setting.Closing_hours;
this.settingItem.Shipping = res.setting.Shipping;
this.settingItem.Packaging = res.setting.Packaging;
setTimeout(() => Loading.hide(), 1000);
let msg = "تنظیمات دریافت شد";
this.toastr.show(msg, "تنظیمات");
}
},
(err) => {
console.log(err);
let errMsg = "خطا رح داد لاگ را نگاه کنید";
let errFullMsg = "خطا در لاگ مرورگر";
let errFullMessage = err.error.message ? err.error.message : errFullMsg;
this.toastr.success(errFullMessage, errMsg);
}
);
}
sometimes this returned object is: {}
and when i seek in console the value is {}
how can i detect it? when this value is an empty object
You can use Object.keys()
if(Object.keys(obj).length === 0) { //Object is empty }
You can use object.entries() function, Its used like this
Object.entries(objectToCheck)
If it returns an empty array, means it is empty ( returning empty array means the object does not have any enumerable property).
Object.entries(objectToCheck).length === 0
then do your required set of tasks.
For checking if object is really an object you can check if its constructor is the Object object like below
objectToCheck.constructor === Object

An array returns the correct values but when called later returns all values as 'undefined'

I have a bunch a JSON files and my code reads the files and stores them into and array, When console logging the array i get the correct values and after but rendering a page, I console logged the array again the all of its values were 'undefined'.
let place = [];
let key, count = 0;
function Search(req, res){
let fileName = getFileName(req, res);
let emirate = req.body.emirate;
let type = req.body.type;
if(emirate == undefined || type == undefined){
req.flash('error', 'Please fill in the form');
res.redirect('/')
}else{
fs.readFile(`./places_files/${emirate}/${fileName}.json`, function(err, data){
if(err){
console.log(err);
}else{
let rawData = JSON.parse(data);
for(key in rawData.places){
place[count] = rawData.places[count]
count++;
}
console.log(place) // returns all of the values
res.render('results', {
places: place
});
console.log(place); // returns all values as undefined
}
});
}
}
Your res.render can mutate your values array.
To prevent this try to send copy of this array like this example:
res.render('results', {
places: place.slice()
});
Another example:
res.render('results', {
places: [...place]
});

Can't compare MongoDB data with javascript array

I want to compare the data which I got from Mongo to javascript array. I am using lodash to compare. But it always return incorrect result.
var editUser = function(userData, getOutFunction) {
var status = CONSTANTS.NG;
checkExistUser(userData._id).then(function(user) {
if (user !== null) {
var userGroup = JSON.stringify(user.group);
user.group = user.group.map((groupId) => {
return groupId.toString();
});
var removedGroups = _.difference(userGroup, userData.group);
var addedGroups = _.difference(userData.group, userGroup);
console.log('Removed Groups: ', removedGroups);
console.log('Added Groups: ', addedGroups);
} else {
status = CONSTANTS.NG;
logger.debug(DEBUG_CLASS_NAME, "Cannot find object");
if (typeof(getOutFunction) !== 'undefined') {
getOutFunction(status, null);
} else {
NO_CALLBACK();
}
}
}).catch(function() {
console.log('Promise is error');
});
var checkExistUser = function(userId) {
return new Promise(function(resolve, reject) {
UserDAO.findById(userId, function(err, user) {
if (err) {
logger.debug(DEBUG_CLASS_NAME, {
name: err.name,
code: err.code,
message: err.message,
method: "checkExist"
});
resolve(null);
} else {
resolve(user);
}
});
});
}
For example:When I try to input value for lodash difference function
var user.group = ["58b8da67d585113517fed34e","58b8da6ed585113517fed34f"];
var userData.group = [ '58b8da67d585113517fed34e' ];
I want lodash difference return below result:
Removed Groups: ['58b8da6ed585113517fed34f']
Added Groups: []
However, the function gave me the result like:
Removed Groups: []
Added Groups: [ '58b8da67d585113517fed34e' ]
Can anyone help me in this case?
I will do appreciate it.
I have had this issue as well, the result from mongodb is an ObjectId type so you can compare the someObjectId.toString() value with your array of strings, or you could use
someObjectId.equals(stringOrObjectIdValue)
However, if you want to keep using lodash functions you will either have to force both arrays to strings or to ObjectIds before passing them into the function.

How to store data from firebaselistobservable to an array?

I'm trying to copy the data from firebase to an array using angular 2. But i'm unable to push the data into the array.
Here's the code:
Variables:
uid: string = '';
agencyItems: FirebaseListObservable<any[]>;
trackerItems: FirebaseListObservable<any[]>;
agencyID: any[] = [];
getData()
this.af.auth.subscribe(auth => {
if (auth) {
this.uid = auth.auth.uid;
}
});
this.getAgencyData();
console.log("AgentID: ",this.agencyID);
console.log("Array Length = ",this.agencyID.length); //PROBLEM HERE: Array agencyID is still 0.
this.getTrackerData();
getAgencyData():
console.log("Fetching agency data");
this.agencyItems = this.af.database.list('/agencies/',{preserveSnapshot:true});
this.agencyItems.subscribe(snapshots => {
snapshots.forEach(snapshot => {
console.log(snapshot.val()._id);
this.agencyID.push(snapshot.val()._id);
});
});
getTrackerData():
for (let i = 0; i < this.agencyID.length; i++)
{
console.log("Fetching Tracker data");
this.trackerItems = this.af.database.list('/tracker/' + this.agencyID[i]);
this.trackerItems.subscribe(trackerItems => trackerItems.forEach(Titem =>
console.log("Tracker name: " + Titem.name),
));
}
Here is the debug console screenshot:
Since i'm a newbie to web programming some code may seem completely unnecessary.
What am I doing wrong in this code? How can I implement the same.
The problem is the location where, or better WHEN, you are checking the length of the array. You make an asynchronous call when you fetch the data, but you are checking the length of the array before the data has been returned. Therefore the array is still empty.
Try the following in getAgencyData():
console.log("Fetching agency data");
this.agencyItems = this.af.database.list('/agencies/',{preserveSnapshot:true});
this.agencyItems.subscribe(snapshots => {
snapshots.forEach(snapshot => {
console.log(snapshot.val()._id);
this.agencyID.push(snapshot.val()._id);
console.log("Array Length = ",this.agencyID.length); // See the length of the array growing ;)
});
// EDIT
this.getTrackerData();
});

Resources