setItem in AsyncStorage doesn't work - reactjs

I'm trying to upload some data to the server from React Native. The data is stored in AsyncStorage.
The data is as follows :
let vehicles = [
{
"id": 1,
"make_text": "Peugeot",
"model_text": "208",
"color_text": "Argent",
"category_text": "CT",
"tag_text": "",
"vin": "123456",
"registration": "",
"reference": "",
"comment": "",
"autralis_id": 151390
},
{
"id": 1,
"make_text": "Peugeot",
"model_text": "307",
"color_text": "Bleu",
"category_text": "CT",
"tag_text": "",
"vin": "654321",
"registration": "",
"reference": "",
"comment": "",
"autralis_id": 156413
}
]
And
let vehicle_slots = [
{
"vehicle_id": 1,
"slot_id": 118,
"area": "",
"zone": "B",
"aisle": "",
"side": "S",
"col": 2,
"level": 0,
"position": 0,
"timestamp": "201705021544",
"picturepath": "",
"pictureguid": "0a016bb9-b7bb-4dd7-a0bf-407ef31a0c1a",
"reason": "ENTER",
"handled": 0,
"uploaded": 0
},
{
"vehicle_id": 1,
"slot_id": 2521,
"area": "",
"zone": "C",
"aisle": "",
"side": "E",
"col": 4,
"level": 0,
"position": 0,
"timestamp": "201705021544",
"picturepath": "",
"pictureguid": "64c726e2-37ec-4ab7-8b57-b08e9899086a",
"reason": "ENTER",
"handled": 0,
"uploaded": 0
}
]
I want to send only those which have uploaded and handled property equals to 0.
Thus, first I get those values where uploaded and handled property is equal to 0. I do it as follows:
try {
let vehicle_data = await AsyncStorage.getItem('vehicle');
if (vehicle_data !== null){
// We have data!!
let vehicle_slot_data = await AsyncStorage.getItem('vehicle_slot');
if (vehicle_slot_data !== null){
vehicle_data = JSON.parse(vehicle_data);
vehicle_slot_data = JSON.parse(vehicle_slot_data);
let result_to_handle = [];
let result_to_upload = [];
vehicle_slot_data.forEach(v => {
let not_handled = vehicle_data.find(m => m.id === v.vehicle_id && v.handled === 0);
let not_uploaded = vehicle_data.find(m => m.id === v.vehicle_id && v.uploaded === 0);
if ( not_uploaded ) result_to_upload.push(that.renderData(v, not_uploaded)[0]);
if ( not_handled ) result_to_handle.push(that.renderData(v, not_handled)[0]);
});
//Here I have result_to_handle and result_to_upload with the data that I need to send to the server.
............
If result_to_handle and result_to_upload have length > 0 then I want to send them to the server and update the property handled and property uploaded to 1 in AsyncStorage.
I try to do it as follows :
..............
if (result_to_handle.length > 0){
let options = {
method: 'POST',
body: JSON.stringify(result_to_handle),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
fetch(data_url + "/manager/transport/sync/movements/", options)
.then(response => response.json())
.then(responseData => {
AsyncStorage.getItem('vehicle_slot')
.then(json => {
let data = [];
if (json) data = JSON.parse(json);
let result = [];
forEach(data, value => {
if( value.handled === 0 ){
value.handled = 1;
result.push(value);
}else{
result.push(value);
}
});
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result))
});
});
}
if (result_to_upload.length > 0){
forEach(result_to_upload, value => {
if (value.picturepath) {
let body = new FormData();
const photo = {
uri: value.picturepath,
type: 'image/jpeg',
name: value.pictureguid + '.jpg',
};
body.append('image', photo);
let xhr = new XMLHttpRequest();
xhr.open('POST', data_url + "/manager/transport/sync/picture/?pictureguid=" + value.pictureguid);
xhr.onload = (e) => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
AsyncStorage.getItem('vehicle_slot')
.then(json => {
if (json){
let data = JSON.parse(json);
let result_data = [];
forEach(data, val => {
if( val.pictureguid === value.pictureguid ){
val.uploaded = 1;
result_data.push(val);
}else{
result_data.push(val);
}
});
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result_data), () => s_cb())
}
});
}
}
};
xhr.onerror = (e) => console.log('Error');
xhr.send(body);
} else {
AsyncStorage.getItem('vehicle_slot')
.then(json => {
if (json){
let data = JSON.parse(json);
let result_data = [];
forEach(data, val => {
if( val.pictureguid === value.pictureguid ){
val.uploaded = 1;
result_data.push(val);
}else{
result_data.push(val);
}
});
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result_data), () => s_cb())
}
});
}
});
}
But the result that I get is not correct.
The vehicle_slot from AsyncStorage is as follows:
[
{
"vehicle_id": 1,
"slot_id": 118,
"area": "",
"zone": "B",
"aisle": "",
"side": "S",
"col": 2,
"level": 0,
"position": 0,
"timestamp": "201705021544",
"picturepath": "",
"pictureguid": "0a016bb9-b7bb-4dd7-a0bf-407ef31a0c1a",
"reason": "ENTER",
"handled": 1,
"uploaded": 0
},
{
"vehicle_id": 1,
"slot_id": 2521,
"area": "",
"zone": "C",
"aisle": "",
"side": "E",
"col": 4,
"level": 0,
"position": 0,
"timestamp": "201705021544",
"picturepath": "",
"pictureguid": "64c726e2-37ec-4ab7-8b57-b08e9899086a",
"reason": "ENTER",
"handled": 1,
"uploaded": 1
}
]
Thus, for the first object is the value uploaded still equal to 0 but it should be equal to 1.
Any advice?

Related

display all documents from a collection react firebase

I have a collection named "journee", and i want to build a list with all elements inside so i get all the data like this :
export async function getAllJournaux() {
const journaux = {};
const querySnapshot = await getDocs(collection(db, "journaux"));
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
// console.log(doc.id, " => ", doc.data());
journaux[doc.id] = doc.data();
});
return journaux;
}
Then on my page getIt witn an useEffect like :
const [journaux, setJournaux] = React.useState();
useEffect(() => {
const getJournaux = async () => {
try {
const getJournaux = await getAllJournaux();
setJournaux(getJournaux);
} catch(error) {
// handle any rejections/errors/etc
}
};
getJournaux(); // <-- fetch/compute coupeur value
}, []);
if (!journaux){
console.log("wait"); // or loading indicator/etc
}else{
console.log(journaux);
}
But how to make a list with the data on my screen , for the moment i just access it with console.log.
The outpout of console.log
{
"8SlEz4CslmTMSxWuqB8W2lDICwj22022-05-02": {
"date": "2022-05-02",
"billetage": {
"5": 0,
"10": 0,
"25": 0,
"50": 0,
"100": 0,
"200": 0,
"250": 0,
"500": 0,
"1000": "2",
"2000": "3",
"5000": "4",
"10000": "5"
},
"pt": "3400000",
"at": "30000",
"vt": "450000",
"coupeur": "qKh2entwU7YD0wcxWRI3"
},
"8SlEz4CslmTMSxWuqB8W2lDICwj22022-05-03": {
"at": "555",
"date": "2022-05-03",
"coupeur": "YuYRYzWj4CVidsmAjO1d",
"vt": "334",
"pt": "5555"
},
"KiuU1xQaKWTAx5mt9XL8vBpY3Y822022-03-01": {
"pt": "150000",
"vt": "450000",
"date": "2022-03-01",
"at": "3000",
"billetage": {
"5": "5",
"10": "3",
"25": "5",
"50": "1",
"100": "2",
"200": "4",
"250": "2",
"500": "3",
"1000": "6",
"2000": "3",
"5000": "4",
"10000": "2"
},
"coupeur": "Ad5g5AE2HdqbZGzhu7G5"
},
"KiuU1xQaKWTAx5mt9XL8vBpY3Y822022-05-11": {
"coupeur": "qKh2entwU7YD0wcxWRI3",
"billetage": {
"5": 0,
"10": 0,
"25": 0,
"50": 0,
"100": 0,
"200": 0,
"250": 0,
"500": 0,
"1000": 0,
"2000": "5",
"5000": "3",
"10000": "10"
},
"pt": "30000",
"date": "2022-05-11",
"at": "100",
"vt": "200000"
},
"KiuU1xQaKWTAx5mt9XL8vBpY3Y822022-05-23T14:03": {
"date": "2022-05-23T14:03",
"pt": "50000",
"coupeur": "",
"at": "130000",
"vt": "200000",
"billetage": {
"5": 0,
"10": 0,
"25": 0,
"50": 0,
"100": 0,
"200": 0,
"250": 0,
"500": 0,
"1000": 0,
"2000": "3",
"5000": "5",
"10000": "2"
}
}
}
Thank you
getAllJournaux is returning an object, so you have to use Object.keys to iterate
const Component = () => {
const [journaux, setJournaux] = useState();
useEffect(() => {
const getJournaux = async () => {
try {
const getJournaux = await getAllJournaux();
setJournaux(getJournaux);
} catch (error) {}
};
getJournaux();
}, []);
return <ul>
{Object.keys(journaux || {}).map(item => (
<li>{item.coupeur}</li>
))}
</ul>
};
const Component = () => {
const [journaux, setJournaux] = useState();
useEffect(() => {
const getJournaux = async () => {
try {
const getJournaux = await getAllJournaux();
setJournaux(getJournaux);
} catch (error) {}
};
getJournaux();
}, []);
// Change .prop1 to a property found in each object of the list
return <ul>
{(journaux || []).map(item => (
<li>{item.prop1}</li>
))}
</ul>
};

How to get a record from an array result of API in React Native with condition?

This is the result JSON file from API:
{
"data": [
{
"recordid": "8888abc",
"accountno": "00-00-00000-00007-00",
"tag": "govid",
"filename": "gov_id.png",
"path": "C:\\MOBILEAPP\\governmentid/gov_id.png",
"ext": ".png",
"posted_dt": "12/11/2019 10:38:20 AM"
},
{
"recordid": "8888abc",
"accountno": "00-00-00000-00007-00",
"tag": "compid",
"filename": "compid.jpg",
"path": "C:\\MOBILEAPP\\compid/cid.jpg",",
"ext": ".jpg",
"posted_dt": "12/11/2019 10:38:20 AM"
}
],
"error_message": "Successfully retrieved.",
"is_success": true,
"requested_on": "12/18/2019 2:14:27 PM"
}
I need to get the path where tag = 'govid' to be puth in a variable because it is used in the header of another API fetching.
async getProfilePhotoPath(token) {
//membid is recordid
let membid = await AsyncStorage.getItem(MEMBER_ID);
let resp2 = await fetch("https://api/files",
{
method: 'GET',
headers: {
"Authorization": "Bearer " + token,
"MemberID": membid,
'Content-Type': 'application/json;charset=UTF-8',
},
},
)
.then(resp2 => {
let respImg = resp2.json();
varImagePath = "should contain data.path where tag = 'govid'"
console.log('This is respImg values',respImg)
return respImg;
})
.catch(error => {
alert('Error in resp2 imgpath!' + error);
});
}
async getProfilePhoto() {
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
this.getProfilePhotoPath(token);
let resp = await fetch("https://api/filepathtoimage", {
headers: {
"Authorization": "Bearer " + token,
"ImagePath": varImagePath,
}
})
let respBlob = await resp.blob();
let reader = new FileReader()
reader.readAsDataURL(respBlob)
reader.onload = () => {
this.setState({ imgsrc: reader.result })
}
}
console.log('This is respImg values',respImg) returns:
This is respImg values
Promise {_40: 0, _65: 0, _55: null, _72: null}
_40: 1
_65: 1
_55:
data: Array(2)
0: {recordid: "8888abc", accountno: "00-00-00000-00007-00", tag: "govid", filename: "gov_id.png", path: "C:\\MOBILEAPP\\governmentid/gov_id.png", …}
1: {recordid: "8888abc", accountno: "00-00-00000-00007-00", tag: "compid", filename: "compid.jpg", path: "C:\\MOBILEAPP\\compid/cid.jpg", …}
length: 2
__proto__: Array(0)
error_message: "Successfully retrieved."
is_success: true
requested_on: "12/18/2019 3:10:32 PM"
__proto__: Object
_72: null
__proto__: Object
How to I put value on varImagePath (in this example should be 'C:\MOBILEAPP\governmentid/gov_id.png')?
resp2.json() return a promise.
.then(resp2 => resp2.json())
.then(jsonObject => {
const data = jsonObject.data;
const record = data.find(item => item.tag === 'govid');
if (record) {
varImagePath = record.path;
}
})
Just use filter:
let filterString = 'govid';
const result = arr.filter(f => f.tag == filterString);
An example:
let arr = [
{
"recordid": "8888abc",
"accountno": "00-00-00000-00007-00",
"tag": "govid",
"filename": "gov_id.png",
"path": "C:\\MOBILEAPP\\governmentid/gov_id.png",
"ext": ".png",
"posted_dt": "12/11/2019 10:38:20 AM"
},
{
"recordid": "8888abc",
"accountno": "00-00-00000-00007-00",
"tag": "compid",
"filename": "compid.jpg",
"path": "C:\\MOBILEAPP\\compid/cid.jpg",
"ext": ".jpg",
"posted_dt": "12/11/2019 10:38:20 AM"
}
]
let filterString = 'govid';
const result = arr.filter(f => f.tag == filterString);
console.log(result);
UPDATE:
In your response:
then(resp2 => {
let respImg = resp2.json();
let arr = respImg.data;
let filterString = 'govid';
const result = arr.filter(f => f.tag == filterString);
return respImg;
})

Response duplicated but the count shows as 1

Using Dynamoose ORM with Serverless. I have a scenario where I'm finding user information based on recommendation.
The response is as follows
{
"data": {
"results": [
{
"specialTip": "Hello World",
"recommendation": "Huli ka!",
"poi": {
"uuid": "poi_555",
"name": "Bukit Panjang",
"images": [
{
"url": "facebook.com",
"libraryUuid": "2222",
"uuid": "9999"
}
]
},
"uuid": "i_8253578c-600d-4dfd-bd40-ce5b9bb89067",
"headline": "Awesome",
"dataset": "attractions",
"insiderUUID": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"insiderInfo": [
{
"gender": "m",
"funFacts": [
{
"type": "knock knock!",
"answer": "Who's there?"
}
],
"profileImage": "newImage.jpg",
"shortDescription": "Samething",
"fullDescription": "Whatever Description",
"interests": [
"HELLO",
"WORLD"
],
"tribes": [
"HELLO",
"WORLD"
],
"uuid": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"personalities": [
"HELLO",
"WORLD"
],
"travelledCities": [
"HELLO",
"WORLD"
]
}
]
},
{
"specialTip": "Hello World",
"recommendation": "Huli ka!",
"poi": {
"uuid": "poi_555",
"name": "Bukit Panjang",
"images": [
{
"url": "facebook.com",
"libraryUuid": "2222",
"uuid": "9999"
}
]
},
"uuid": "i_8253578c-600d-4dfd-bd40-ce5b9bb89067",
"headline": "Awesome",
"dataset": "attractions",
"insiderUUID": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"insiderInfo": [
{
"gender": "m",
"funFacts": [
{
"type": "knock knock!",
"answer": "Who's there?"
}
],
"profileImage": "newImage.jpg",
"shortDescription": "Samething",
"fullDescription": "Whatever Description",
"interests": [
"HELLO",
"WORLD"
],
"tribes": [
"HELLO",
"WORLD"
],
"uuid": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"personalities": [
"HELLO",
"WORLD"
],
"travelledCities": [
"HELLO",
"WORLD"
]
}
]
}
],
"count": 1
},
"statusCode": 200
}
Not sure where I'm going wrong as the items in the response seems to be duplicated but the count is 1.
Here is the code
module.exports.index = (_event, _context, callback) => {
Recommendation.scan().exec((_err, recommendations) => {
if (recommendations.count == 0) {
return;
}
let results = [];
recommendations.forEach((recommendation) => {
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => {
if (insider.count == 0) {
return;
}
recommendation.insiderInfo = insider;
results.push(recommendation);
});
});
const response = {
data: {
results: results,
count: results.count
},
statusCode: 200
};
callback(null, response);
});
};
EDIT: My previous code ignored the fact that your "Insider" query is asynchronous. This new code handles that and matches your edit.
const async = require('async'); // install async with 'npm install --save async'
[...]
module.exports.index = (_event, _context, callback) => {
Recommendation.scan().exec((_err, recommendations) => {
if (_err) {
console.log(_err);
return callback(_err);
}
if (recommendations.count == 0) {
const response = {
data: {
results: [],
count: 0
},
statusCode: 200
};
return callback(null, response);
}
let results = [];
async.each(recommendations, (recommendation, cb) => { // We need to handle each recommendation asynchronously...
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => { // because this is asynchronous
if (_err) {
console.log(_err);
return callback(_err);
}
if (insider.count == 0) {
return cb(null);
}
recommendation.insiderInfo = insider;
results.push(recommendation);
return cb(null);
});
}, (err) => { // Once all items are handled, this is called
if (err) {
console.log(err);
return callback(err);
}
const response = { // We prepare our response
data: {
results: results, // Results may be in a different order than in the initial `recommendations` array
count: results.count
},
statusCode: 200
};
callback(null, response); // We call our main callback only once
});
});
};
Initial (partly incorrect) answer, for reference.
You are pushing the result of your mapping into the object that you are currently mapping and callback is called more than once here. That's a pretty good amount of unexpected behavior material.
Try the following:
let results = [];
recommendations.forEach((recommendation) => {
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => {
if (insider.count == 0) {
return;
}
recommendation.insiderInfo = insider;
results.push(recommendation);
});
});
let response = {
data: {
results: results,
count: results.count
},
statusCode: 200
};
callback(null, response);

Vue.Js - How to parse integer array object data

I've a response data in array object
here my response code :
{
"data": [
{
"id": 7,
"product_name": "iPad",
"rating": "4.00"
},
{
"id": 2,
"product_name": "iPhone",
"rating": "3.00"
},
{
"id": 8,
"product_name": "iPod",
"rating": "7.00"
},
{
"id": 4,
"product_name": "iMac",
"rating": "9.00"
}
],
"status": 200,
"error": 0
}
and then i try to map the array object to parse the data 'rating' to integer, here my axios code :
getCustomerType: function(store) {
this.loading = true
let headers = {
Authorization: 'Bearer ' + window.accessToken
}
axios({
method: 'GET',
url: baseApi(this.selectedStore.url_id, 'en', 'customertype'),
params: this.params,
headers: headers
})
.then(response => {
this.customerTypeData = response.data.data
for (let index = 0; index < this.customerTypeData.length; index++) {
this.customerTypeData.rating[index] = parseInt(this.customerTypeData.rating[index])
}
this.loading = false
})
}
But the code of parseInt it doesn't make it solve
for (let index = 0; index < this.customerTypeData.length; index++) {
this.customerTypeData.rating[index] = parseInt(this.customerTypeData.rating[index])
}
Expected :
rating (by index) it change from string to number by index array

Unit testing AngularJS service method thet resolves multiple promises with $q.all

I am trying to test the following service method that calls another method to retrieve data multiple times with different parameters.
I have only ever tested resolving one promise at a time so am not sure how to approach this method as a karma/jasmine unit test:
getMappings(dealerId){
let dfd = this.$q.defer();
let promises = [];
promises.push(this.DataService.getTranslationMappings(this.TRANSLATIONS.DEALER, dealerId));
promises.push(this.DataService.getTranslationMappings(this.TRANSLATIONS.DAYCOUNT, dealerId));
promises.push(this.DataService.getTranslationMappings(this.TRANSLATIONS.FREQUENCY, dealerId));
promises.push(this.DataService.getTranslationMappings(this.TRANSLATIONS.RATE_STATIC, dealerId));
promises.push(this.DataService.getTranslationMappings(this.TRANSLATIONS.SETTLEMENT_TYPE, dealerId));
this.$q.all(promises)
.then((resp) => {
dfd.resolve({
dealers: resp[0].data,
daycounts: resp[1].data,
frequencies: resp[2].data,
rateStatics: resp[3].data,
settlementTypes: resp[4].data
});
}, (resp) => {
dfd.reject(resp);
});
return dfd.promise;
}
Any help would be appreciated. Thanks :)
it('should get the mappings for listing', () => {
let dealerId = 1;
let resp;
let count = 0;
let dealers = [
{
"id": 1,
"dealerId": 1,
"translation": {
"id": 2,
"description": "Wayne Enterprise"
},
"synonym": "CTRPTYCODE 1"
}
];
let daycount = [
{
"id": 1,
"dealerId": 1,
"translation": {
"id": 1,
"description": "DAYCT 1"
},
"synonym": "DAYCTCODE 1"
}
];
let frequency = [
{
"id": 1,
"dealerId": 1,
"translation": {
"id": 1,
"description": "FREQ A"
},
"synonym": "FREQCODE 1"
}
];
let ratestat = [
{
"id": 1,
"dealerId": 1,
"translation": {
"id": 1,
"description": "RATESTAT 1"
},
"synonym": "RATESTATCODE 1"
}
];
let settlement = [
{
"id": 1,
"dealerId": 1,
"translation": {
"id": 1,
"description": "SETTYPE A"
},
"synonym": "SETTYPECODE 1",
"$$hashKey": "object:221"
}
];
spyOn(service, 'getMappings').and.callThrough();
spyOn(DataService, 'getTranslationMappings').and.callFake(function(){
var defer = this.$q.defer();
let data;
switch(count) {
case 0:
data = dealers;
break;
case 1:
data = daycount;
break;
case 2:
data = frequency;
break;
case 3:
data = ratestat;
break;
case 4:
data = settlement;
break;
}
defer.resolve({
success: true,
error: null,
data: data
});
count++;
return defer.promise;
});
service.getMappings(dealerId).then((data) => {
resp = data;
});
scope.$digest();
expect(service.getMappings).toHaveBeenCalled();
expect(service.getMappings).toHaveBeenCalledWith(dealerId);
expect(DataService.getTranslationMappings).toHaveBeenCalled();
expect(DataService.getTranslationMappings.calls.count()).toEqual(5);
expect(DataService.getTranslationMappings.calls.argsFor(0)).toEqual(['DEALER', dealerId]);
expect(DataService.getTranslationMappings.calls.argsFor(1)).toEqual(['DAYCOUNT', dealerId]);
expect(DataService.getTranslationMappings.calls.argsFor(2)).toEqual(['FREQUENCY', dealerId]);
expect(DataService.getTranslationMappings.calls.argsFor(3)).toEqual(['RATE_STATIC', dealerId]);
expect(DataService.getTranslationMappings.calls.argsFor(4)).toEqual(['SETTLEMENT_TYPE', dealerId]);
expect(resp.dealers).toEqual(dealers);
expect(resp.daycounts).toEqual(daycount);
expect(resp.frequencies).toEqual(frequency);
expect(resp.rateStatics).toEqual(ratestat);
expect(resp.settlementTypes).toEqual(settlement);
});
Solved! :)

Resources