Perform a POST request in the background using React Native (expo) - react-native

I am relatively new to React Native but I have a functional codebase. My app sends orders from the waiter to the kitchen. I have tested it in stores. What I need is to somehow post the order to my web app without waiting for the server to respond (assuming that all is ok) and navigate directly to the list of tables some sort of async/background job. Do I implement this using some background tasks? if yes could you point in the right direction? Also if possible no redux answers I don't know how to use it yet.
Sorry for the messy code I'm getting better.
onSendOrder = () => {
//console.log('Sending Order');
//console.log("table_id", this.props.navigation.getParam("table_id"));
// trim the contents.
let order_items = this.state.order;
// //console.log(order_items);
// const myArray = this.state.data.filter(function( obj ) {
// return obj.checked !== false;
// });
var i;
// let total_cost = 0;
let contents = []
// //console.log('total_cost: ', total_cost);
// let items = order.items;
for (i = 0; i < order_items.length; i++) {
contents = order_items[i].contents.filter(function( obj ) {
return obj.checked !== false;
});
// //console.log(contents);
order_items[i].contents = contents;
// total_cost += this.compute_item_cost(order[i]);
}
this.setState({loading:true});
//console.log('Trimed order items: ',order_items);
let order = {
"items": {
"credentials": this.state.credentials,
"personnel_id": 1,
"store_id": 1,
"order_comment": "",
"order_id": "",
"timestamp": "None",
"table_id": this.props.navigation.getParam("table_id"),
"order_items": order_items
}
};
var host = this.props.navigation.getParam('url', 'something.com');
// //console.log('SENDING ORDER TO HOST: ', host)
//console.log('ORDER OBJECT', order);
fetch("http://" + host + "/api/v1/mobile/order?store_id=1", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(order)
})
.then(response => {
// //console.log(response.status)
// this.props.navigation.navigate('Table', { order: this.state.order });
const statusCode = response.status;
const data = response.json();
return Promise.all([statusCode, data]);
})
.then((server_response) => {
//console.log("RESULTS HERE:", server_response[0])
this.setState({
order: [],
}, function () {
if (server_response[0] == 201) {
//console.log('Success Going to Table')
this.props.navigation.navigate('Table', { order: this.state.order });
} else {
//console.log('Failed going to table')
this.props.navigation.navigate('Table', { order: this.state.order });
}
});
})
.catch((error) => {
//console.error(error);
})
};
}

import * as Notifications from 'expo-notifications';

Related

How do I send token information to the server side with signalR?

var ajaxResponse = $.ajaxQueue({
type: "POST",
url: "/Upload/Upload",
enctype: 'multipart/form-data',
contentType: false,
processData: false,
async: true,
beforeSend: function(request) {
request.setRequestHeader("serviceUrl", getToLocalStorage("serviceUrl"));
request.setRequestHeader("token", getToLocalStorage("token"));
connection.on("lastprogress", function (itemId, progresbar) {
$(".progress-bar").each(function (index, element) {
var fileid = $(this).data("fileid");
if (fileid === itemId) {
$(this).width(progresbar + "%");
}
var obj = CancelUploadFileList.find(el => el == object.itemId);
if (obj) {
$(".progress-bar").each(function (index, element) {
var fileid = $(this).data("fileid");
if (fileid === object.itemId) {
$(this).removeClass("progress-bar");
$(this).parent().removeClass("progress-custom");
$(this).html("<div style='font-weight:normal;'>Canceled</div>");
ajaxResponse.abort();
// $(this).innerHTML("Canceled");
}
});
}
});
// var progressBarValue = $(".progress-custom").find("[data-fileid='" + uploadFileCollectionList[i].itemId + "']").val();
// $('.progress-bar').eq(count - 1).width(progresbar + "%");
//if (progresbar == 100) {
// connection.on("uploadcontrol", function (isboolean, itemId) {
// if (isboolean) {
// $('.remove-from-list').each(function (index, element) {
// if ($(this).data("fileid") === itemId) {
// $(this).removeClass("red").removeClass("stop").addClass("green").addClass("check");
// }
// });
// }
// });
//}
}
);
try {
connection.start().catch(err => console.log(err.toString())).then(response => console.log("connected"));//unutma
} catch (e) {
}
},
headers: { 'serviceUrl': getToLocalStorage("serviceUrl"), 'token': getToLocalStorage("token") },
data: formData,
success: function (data) {
if (data.success) {
UploadControl(newItemId, object.overWrite);
}
else {
$(function () {
new PNotify({
//
text: data.message == null ? object.itemName+" file is empty": data.message,
type: "error",
addClass: ".notifybg",
delay: 5000
});
});
}
},
error: function (data) {
var uploadedFile = uploadFileCollectionListData.findIndex(el => el.itemId == newItemId);
uploadFileCollectionListData.splice(uploadedFile, 1);
}
});
while (bytesToRead > 0)
{
int n = stream.Read(buffer, 0, chunkSize);
if (n == 0) break;
if (n != buffer.Length)
Array.Resize(ref buffer, n);
var newToken= _progressHub.Clients.Client().In
uploadCloudItem = UploadCloudItem(token, new MemoryStream(buffer), u);
bytesRead += n;
bytesToRead -= n;
var progress = (int)((float)bytesRead / (float)uploadRequest.itemSize * 100.0);
_progressHub.Clients.All.SendAsync("lastprogress", u.itemId, progress);
Task.Delay(500);
}
How do I send token information to the server side with signalR?
How do I send token information to the server side with signalR?
I'm uploading files with jquery, but the token expires when the file size is large.
how do i send my current token
How do I send token information to the server side with signalR?
If a website needs to display in real time or so graph the up and down graphs of stocks. They will think of programming so that the browser regularly sends requests to get the latest stock prices from the web server -> Pooling mechanism. If the number of browsers simultaneously accessing thousands, the web server will have to work very hard even if only a few stocks change points, but still have to reply and send back all the stocks. . Instead of letting the client ask the server (pooling) continuously blindly. Why not let the server, if there are changes, will report back to the client, and will only send the necessary data for the client to process (notification)

is there any better way to upload multiple large files on server in Flutter

I am trying to upload multiple files on server in flutter but they are taking to much time to upload.I am using Dio() for uploading..is any better way to upload multiple files on server in flutter.?
I am sending upload function.in which 10 files during upload takes more than 5 minutes
here is my code!
_upLoadFiles() async {
List <FileWithComment> uploadControls = preUpload();
var token = await _getToken();
print("Token: $token");
if (files) {
try {
final result = await InternetAddress.lookup("google.com");
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
FormData data = FormData.fromMap({
"jwt": token,
"comment": [],
"directory": widget.dName,
"directory_id": widget.folderId,
"case_id": widget.case_id,
"media_files": await _mediaFileList(),
});
await Dio()
.post(
"${MyFlutterApp.baseUrl}media_upload.php",
data: data,
onSendProgress: _setUploadProgress,
options: Options(
contentType: "multipart/form-data",
),
)
.then((res) => (res.data))
.then((d) => json.decode(d))
.then((res) => postUpload(res));
}
} on SocketException catch (_) {
_saveLocal(uploadControls);
} catch (e) {
if (e.toString().contains("Cannot retrieve length of file")) {
_showSnackBar("Cannot Upload File Try Again Later", Color(0xffDC0000), Colors.white);
}
}
} else {
print("${widget.dName}");
try {
final result = await InternetAddress.lookup("google.com");
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
FormData data = FormData.fromMap({
"jwt": token,
"directory": widget.dName,
"directory_id": widget.folderId,
"case_id": widget.case_id,
"comment": list.map((filewithcomment) => filewithcomment.comment).toList(),
"media_files": await _mediaFileList(),
"f_location": list.map((filewithcomment) => filewithcomment.location).toList(),
});
await Dio()
.post("${MyFlutterApp.baseUrl}media_upload.php",
data: data,
onSendProgress: _setUploadProgress,
options: Options(
contentType: "multipart/form-data",
))
.then((res) {
return res.data;
})
.then((d) => json.decode(d))
.then((res) => postUpload(res));
}
} on SocketException catch (_) {
_saveLocal(uploadControls);
} catch (e) {
print(e);
if (e.toString().contains("Cannot retrieve length of file")) {
_showSnackBar("Cannot Upload File Try Again Later", Color(0xffDC0000), Colors.white);
}
}
}
}
This is mediafileList()..May be there is issue in these lines of code
Future<List<MultipartFile>> _mediaFileList() async {
Completer complete = Completer<List<MultipartFile>>();
List<MultipartFile> filesList = [];
for (int index = 0; index < list.length; index++) {
if (list[index].file is File) {
var file = list[index].file;
filesList.add(await MultipartFile.fromFile(file.path, filename: file.path.split('/').last));
}
if (list[index].file is String) {
var file = File(list[index].file);
filesList.add(await MultipartFile.fromFile(
file.path, filename: file.path.split('/').last));
}
if (index == list.length - 1) complete.complete(filesList);
}
return complete.future;
}

input file component is not updating, VueJS

I have some code where I update multiple files using a package.
Add / Remove seems to work if I console.log, but if I do a POST request, on server I get all files, even if I delete them.
Example: I add 3 files, I delete 2 of them and I do a POST, on server I get 3 files. (But on console.log it shows me that I have only 1 which is correct).
Also, I find this article , but I am not sure what to do in my case.
This is a short version of my code.
<div id="upload-files-on-update">
<file-upload
:multiple="true"
v-model="certifications"
input-id="certifications"
name="certifications[]"
#input-filter="inputFilter"
ref="upload">
<span class="button">Select files</span>
</file-upload>
</div>
new Vue({
el: '#upload-files-on-update',
data: function () {
return {
certifications: [],
}
},
components: {
FileUpload: VueUploadComponent
},
methods: {
updateFiles(){
let formData = new FormData();
this.certifications.forEach((file, index) => {
if (!file.status && file.blob) {
formData.append("certifications[]",
{
types: this.accept,
certifications_ids: this.certifications_ids,
}
);
this.loadingButton = true;
}
});
axios
.post("<?php echo $link;?>", formData, {
headers: {
"Content-Type": "multipart/form-data"
},
params:{
types: this.accept,
certifications_ids: this.certifications_ids,
}
})
},
inputFilter(newFile, oldFile, prevent) {
if (newFile && !oldFile) {
if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
return prevent()
}
if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
return prevent()
}
}
if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
newFile.blob = ''
let URL = window.URL || window.webkitURL
if (URL && URL.createObjectURL) {
newFile.blob = URL.createObjectURL(newFile.file)
}
newFile.pending = true;
newFile.thumb = ''
if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
newFile.thumb = newFile.blob
}
}
},
// Remove file from table
removeFile(index) {
this.certifications.splice(index, 1);
},
}
});
I found a solution for this problem.
//I catch ajax request and I make sure that is the request that I want it
var self = this;
$.ajaxSetup({
beforeSend: function (xhr,settings) {
if(settings.type != 'POST'){
return ;
}
if(settings.data.get('controller') != 'wcfm-memberships-registration'){
return ;
}
// Here I set file input as an empty array
settings.data.set('certifications[]',[]);
// Here I add my new files from a VueJS array
self.certifications.forEach((file, index) => {
settings.data.append("certifications[]", file.file);
});
}
});
});

How to unit test API calls with axios() in react-native with Jest

I am developing Sample Application in React-native . I used Jest to use unit testing, i don't have an idea about Jest Api call
I want to need without using Promises:
Here this is my Code:
this is My Function Code:
/**
* #description Action to call nilpick service ,on success increment route as well as mark the location as fulfilled
*/
function nilPick() {
return async (dispatch, getState) => {
const currentState = getState();
const { user, picking } = currentState;
const { currentRouteIndex, pickRoute } = getState().picking.pickRouteInfo;
const { workId } = picking.pickWorkInfo;
const nilPickItem = pickRoute[currentRouteIndex];
const currentItem = getCurrentItem(currentState);
const currentTime = dateFunctions.getCurrentUTC();
const nilpickedItem = [
{
orderId: nilPickItem.fulfillOrdNbr,
lineNbr: nilPickItem.ordLine,
pickUpcNbr: nilPickItem.upc,
pickDisplayTs: currentTime,
pickUom: currentItem.workDetail.uom,
pickedLoc: nilPickItem.location,
locationType: nilPickItem.locType,
locId: nilPickItem.locId,
pickByType: currentItem.workDetail.pickByType,
exceptionPick: false,
gtinPrefRankNbr: 0,
pickUpcTypeCd: 5100
}
];
const { status, statusText } = await pickingService.nilPick(nilpickedItem, user, workId);
if (status === 200 || statusText === 'Created') {
console.info('Item nilpicked');
if (currentRouteIndex < pickRoute.length) {
dispatch(incrementRoute());
} else {
Alert.alert(
'Nilpick Complete',
[
{
text: 'OK',
onPress: () => {
dispatch(endPicking());
}
}
],
{ cancelable: false }
);
console.log('End of pickwalk');
return;
}
} else {
console.info('error in nilpicking item ');
}
};
}
This is my code above method to Converting Like this below sample test Case:
This is sample Test i want to call Api How to implement in Jest
it('Test For nillPic', () => {
const initialState = {
picking: {
pickRouteInfo: {
"fulfillOrdNbr": pickRouteInfo.fulfillOrdNbr,
"orderLine": '1',
"upc": '4155405089',
"location": 'A-1-1',
"availableLocsToPick": '2',
'suggSubPendingPicks?': 'N',
'manualSubPendingPicks?': 'N',
"lineFullfilled": 'false',
"currentRouteIndex": 1,
"pickRoute": ['r1', 'r2', 'r3']
}
}
};
// console.log("state data...", initialState);
const store = mockStore(initialState);
store.dispatch(actions.pickRouteActions.nilPickSuccess());
const expectedAction = [{ type: 'INCREMENT_ROUTE' }];
const localActions = store.getActions();
expect(localActions).toEqual(expectedAction);
});
Finally This is my code Please . Thanks in Advance

React Native setItem in storage

I have an forEach loop as follows:
let result_test = [];
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) {
result_test.push(
{
"vehicle_id": value.vehicle_id,
"slot_id": value.slot_id,
"area": value.area,
"zone": value.zone,
"aisle": value.aisle,
"side": value.side,
"col": value.col,
"level": value.level,
"position": value.position,
"timestamp": value.timestamp,
"picturepath": value.picturepath,
"pictureguid": value.pictureguid,
"reason": value.reason,
"handled": value.handled,
"uploaded": 1
}
);
}
}
};
xhr.onerror = (e) => console.log('Error');
xhr.send(body);
} else {
result_test.push(
{
"vehicle_id": value.vehicle_id,
"slot_id": value.slot_id,
"area": value.area,
"zone": value.zone,
"aisle": value.aisle,
"side": value.side,
"col": value.col,
"level": value.level,
"position": value.position,
"timestamp": value.timestamp,
"picturepath": value.picturepath,
"pictureguid": value.pictureguid,
"reason": value.reason,
"handled": value.handled,
"uploaded": 1
}
)
}
});
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result_test), () => s_cb())
And result to upload is as follows:
[
{
aisle:""
area:""
category_text: "CT"
col:2
color_text:"Argent"
comment:""
handled:0
level:0
make_text:"Peugeot"
model_text:"208"
pictureguid:"88e6a87b-b48b-4bfd-b42d-92964a34bef6"
picturepath:
"/Users/boris/Library/Developer/CoreSimulator/Devices/E5DB7769-6D3B-4B02-AA8F-CAF1B03AFCB7/data/Containers/Data/Application/DBCFB503-F8E1-42FF-8C2B-260A713AF7BC/Documents/2D840EFA-014C-48C0-8122-53D9A0F4A88E.jpg"
position:0
reason:"ENTER"
reference:""
registration:""
side:"E"
slot_id:2358
tag_text:""
timestamp:"201705021714"
uploaded:0
vehicle_id:1
vin:"123456"
zone:"A"
},
{
aisle:""
area:""
category_text: "CT"
col:2
color_text:"Argent"
comment:""
handled:0
level:0
make_text:"Golf"
model_text:"208"
pictureguid:"88e6a87b-b48b-4bfd-b42d-92964a34bef6"
picturepath:""
position:0
reason:"ENTER"
reference:""
registration:""
side:"B"
slot_id:2358
tag_text:""
timestamp:"201705021714"
uploaded:0
vehicle_id:1
vin:"123456"
zone:"A"
}
]
But for some reason is AsyncStorage.getItem("vehicle_slot").then(json => console.log(JSON.parse(json)) only the second object, the first one is not added to storage.
Any advice?
your XMLHttpRequest is going to run asynchronously. It's perfectly possible that your code might get to the
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result_test), () => s_cb())
before the onload event has occurred, since that only happens when the request is done. You should add the setItem as a callback.
resultToUpload.forEach(result => {
if (result.picturepath) {
// handle stuff here
let xhr = new XMLHttpRequest();
xhr.onload = (e) => {
// handle other stuff
result_test.push(/* data */);
await storeInAsyncStorage(result_test, () => s_cb());
};
} else {
// handle even more stuff
result_test.push(/* different data */);
await storeInAsyncStorage(result_test, () => s_cb());
}
});
function storeInAsyncStorage(data, callback) {
if(callback) {
return AsyncStorage.setItem(JSON.stringify(data), callback);
} else {
return AsyncStorage.setItem(JSON.stringify(data));
}
}
You should also be aware that AsyncStorage.setItem is asynchronous. The item does not get set immediately, and the setItem method returns a promise that resolves when the item is set. Try using await AsyncStorage.setItem if you're not passing it into some other function.