What is the best way to store multiple Axios requests in VueX? - vue.js

I'm new to Vue and i would like to know how can i get data from multiple requests , store it in an object, and then preform some manipulations to the data...(format dates, add currency properties, etc..)
For example:
Suppose these are my requests:
'https://jsonplaceholder.typicode.com/posts/1'
'https://jsonplaceholder.typicode.com/posts/2'
'https://jsonplaceholder.typicode.com/posts/3'
So i want to do something like :
Set a state variable to store all the id's for looping it later on
state: {
ids:[1,2,3],
posts:[],
alteredPostsArr :[]
},
Loop the requests and store all the data
var dataStored = [];
var ids = this.state.ids
for(var i=0; i< ids.length; i++){
axios
.get('https://jsonplaceholder.typicode.com/posts/'+ids[i])
.then(function(response){
dataStored.push(response.data)
console.log(response.data);
})
}
this.state.posts = dataStored // store all results
Create a function that manipulates the data... something like
setDate :function(data){ // loop over this.state.posts
for(var i=0; i< data.length; i++){
var newDataObj = {
"userId": data[i].userId,
"id": data[i].id,
"title": data[i].title,
"body": data[i].body,
"date":new Date(),
}
this.state.alteredPostsArr.push(newDataObj )
}
}
I've look into vuex tutorials but i don't understand where should i put the axios requests loop... so i've tried to put it in the Actions, like here, but i get empty arrays.....
export default new Vuex.Store({
state: {
posts:[],
ids:[1,2,3],
alteredPostsArr:[],
},
methods:{
setDate:function(data){
// loop over this.state.posts
for(var i=0; i< data.length; i++){
var newDataObj = {
"userId": data[i].userId,
"id": data[i].id,
"title": data[i].title,
"body": data[i].body,
"date":new Date(),
}
this.state.alteredPostsArr.push(newDataObj )
}
}
},
actions: {
loadPosts ({ commit }) {
var dataStored = [];
var ids = this.state.ids
for(var i=0; i< ids.length; i++){
axios
.get('https://jsonplaceholder.typicode.com/posts/'+ids[i])
.then(function(response){
dataStored.push(response.data)
})
}
this.state.posts = dataStored // store all results
}
},
mutations: {
SET_POSTS (state, posts) {
state.posts = posts
}
}

Related

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

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';

Using Mongoose query outside exec function

I am trying to use the result of a query outside the exec function, but I can't seem to get it working
This is my function in Express
getUrlsFromDatabase = function(){
blog.find()
.select('url')
.exec(function(err,docs){
var sitemap = [];
for(var i=0; i<docs.length; i++) {
sitemap.push(docs[i].url);
}
return sitemap
})
console.log("Trying to get result docs here")
}
Try using async/await
getUrlsFromDatabase = async function(){
var blogs = await blog.find().select('url')
var sitemap = [];
for(var i=0; i<docs.length; i++) {
sitemap.push(docs[i].url);
}
return sitemap
console.log("Trying to get result docs here")
}
Update:
Or just add a return to back some result from the function
getUrlsFromDatabase = function(){
return blog.find() // <- add return here
.select('url')
.exec(function(err,docs){
var sitemap = [];
for(var i=0; i<docs.length; i++) {
sitemap.push(docs[i].url);
}
return sitemap
})
console.log("Trying to get result docs here")
}
Or just save It in a variable:
getUrlsFromDatabase = function(){
const result = blog.find() // <- add variable here
.select('url')
.exec(function(err,docs){
var sitemap = [];
for(var i=0; i<docs.length; i++) {
sitemap.push(docs[i].url);
}
return sitemap
})
return result // to return it outbound
}

Clear JQuery DataTable Local Storage

How to clear Jquery Datatable Local Storage programmatically?
localstorage.clear() clears all localstorage.
But I need to clear the datatable values specifically.
<i class="fas fa-sync-alt RefreshButtonDataTable" onclick="ClearDataTableStorageAndRefresh()"></i>
<script>
function ClearDataTableStorageAndRefresh() {
ClearLocalStorageDataTables_tbl();
$('#tbl_SearchTasks').DataTable().ajax.reload();
}
</script>
function ClearLocalStorageDataTables_tbl() {
debugger;
var arr = []; // Array to hold the keys
// Iterate over localStorage and insert the keys that meet the condition into arr
for (var i = 0; i < localStorage.length; i++) {
if (localStorage.key(i).substring(0, 14) == 'DataTables_tbl') {
arr.push(localStorage.key(i));
}
}
// Iterate over arr and remove the items by key
for (var i = 0; i < arr.length; i++) {
localStorage.removeItem(arr[i]);
}
new Noty({
type: 'success',
theme: 'metroui',
layout: 'bottomRight',
text: 'Datatable Temporary Storage Cleared',
progressBar: true,
timeout: 5000
}).show();
}

QZ TRAY PRINITING ORDER NOT IN SEQ

I'm trying to print qz tray from javascript.
I have barcode with number in ascending order 1,2,3,4, 5 and so on.
I looping the seq correctly . but when printed out, it was not in order.
setTimeout("directPrint2()",1000);
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function directPrint2(){
var data;
var xhttp;
var v_carton = "' || x_str_carton ||'";
var carton_arr = v_carton.split('','');
var v1 = "' ||
replace(x_zebra_printer_id, '\', '|') ||
'".replace(/\|/g,"\\");
if(v1 == ""){
alert("Please setup ZPL Printer");
}
else{
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = [ toNative(this.responseText) ];
printZPL(data, v1);
}
};
for (var j = 0; j < carton_arr.length; j++){
var url = "' || x_wms_url ||
'WWW_URL.direct_print_label?in_carton_no="+toValidStr(carton_arr[j]);
xhttp.open("GET", url, false);
xhttp.send();
sleep(5000);
}
}
};
',
'javascript'
What's missing from your example:
I do not see any looping logic in the example calling the printZPL function,
printZPL isn't a QZ Tray function and you're missing the code snippet which it calls. Usually this would be qz.print(config, data);.
Regardless of the missing information, the qz.print(...) API is ES6/Promise/A+ based meaning if you want to call qz.print multiple times in a row you need to use a Promise-compatible technique. (e.g. .then(...) syntax) between your print calls as explained in the Chaining Requests guide.
To avoid this, you can concatenate all ZPL data into one large data array. Be careful not to spool too much data at once.
If you know exactly how many jobs you'll be appending, you can hard-code the promise chain:
qz.websocket.connect()
.then(function() {
return qz.printers.find("zebra"); // Pass the printer name into the next Promise
})
.then(function(printer) {
var config = qz.configs.create(printer); // Create a default config for the found printer
var data = ['^XA^FO50,50^ADN,36,20^FDRAW ZPL EXAMPLE^FS^XZ']; // Raw ZPL
return qz.print(config, data);
})
.catch(function(e) { console.error(e); });
Finally, if you do NOT know in advanced how many calls to qz.print(...) you can use a Promise loop as explained in the Promise Loop guide.
function promiseLoop() {
var data = [
"^XA\n^FO50,50^ADN,36,20^FDPRINT 1 ^FS\n^XZ\n",
"^XA\n^FO50,50^ADN,36,20^FDPRINT 2 ^FS\n^XZ\n",
"^XA\n^FO50,50^ADN,36,20^FDPRINT 3 ^FS\n^XZ\n",
"^XA\n^FO50,50^ADN,36,20^FDPRINT 4 ^FS\n^XZ\n"
];
var configs = [
{ "printer": "ZDesigner LP2844-Z" },
{ "printer": "ZDesigner LP2844-Z" },
{ "printer": "ZDesigner LP2844-Z" },
{ "printer": "ZDesigner LP2844-Z" }
];
var chain = [];
for(var i = 0; i < data.length; i++) {
(function(i_) {
//setup this chain link
var link = function() {
return qz.printers.find(configs[i_].printer).then(function(found) {
return qz.print(qz.configs.create(found), [data[i_]]);
});
};
chain.push(link);
})(i);
//closure ensures this promise's concept of `i` doesn't change
}
//can be .connect or `Promise.resolve()`, etc
var firstLink = new RSVP.Promise(function(r, e) { r(); });
var lastLink = null;
chain.reduce(function(sequence, link) {
lastLink = sequence.then(link);
return lastLink;
}, firstLink);
//this will be the very last link in the chain
lastLink.catch(function(err) {
console.error(err);
});
}
Note: The Promise Loop is no longer needed in QZ Tray 2.1. Instead, since 2.1, an array of config objects and data arrays can be provided instead.

Vue.js list not updating when data changes

i'm trying re-organised a list of data. I have given each li a unique key, but still, no luck!
I have had this working before exactly like below, think i'm cracking up!
let app = new Vue({
el: '#app',
data: {
list: [
{ value: 'item 1', id: '43234r' },
{ value: 'item 2', id: '32rsdf' },
{ value: 'item 3', id: 'fdsfsdf' },
{ value: 'item 4', id: 'sdfg543' }
]
},
methods: {
randomise: function() {
let input = this.list;
for (let i = input.length-1; i >=0; i--) {
let randomIndex = Math.floor(Math.random()*(i+1));
let itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
this.list = input;
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<ul>
<li v-for="item in list" :key="item.id">{{ item.value }}</li>
</ul>
Randomize
</div>
Edit:
Thanks for the answers, to be honest the example I provided may not have been the best for my actual issue I was trying to solve. I think I may have found the cause of my issue.
I'm basically using a similar logic as above, except i'm moving an array of objects around based on drag and drop, this works fine with normal HTML.
However, i'm using my drag and drop component somewhere else, which contains ANOTHER component and this is where things seem to fall apart...
Would having a component within another component stop Vue from re-rendering when an item is moved within it's data?
Below is my DraggableBase component, which I extend from:
<script>
export default {
data: function() {
return {
dragStartClass: 'drag-start',
dragEnterClass: 'drag-enter',
activeIndex: null
}
},
methods: {
setClass: function(dragStatus) {
switch (dragStatus) {
case 0:
return null;
case 1:
return this.dragStartClass;
case 2:
return this.dragEnterClass;
case 3:
return this.dragStartClass + ' ' + this.dragEnterClass;
}
},
onDragStart: function(event, index) {
event.stopPropagation();
this.activeIndex = index;
this.data.data[index].dragCurrent = true;
this.data.data[index].dragStatus = 3;
},
onDragLeave: function(event, index) {
this.data.data[index].counter--;
if (this.data.data[index].counter !== 0) return;
if (this.data.data[index].dragStatus === 3) {
this.data.data[index].dragStatus = 1;
return;
}
this.data.data[index].dragStatus = 0;
},
onDragEnter: function(event, index) {
this.data.data[index].counter++;
if (this.data.data[index].dragCurrent) {
this.data.data[index].dragStatus = 3;
return;
}
this.data.data[index].dragStatus = 2;
},
onDragOver: function(event, index) {
if (event.preventDefault) {
event.preventDefault();
}
event.dataTransfer.dropEffect = 'move';
return false;
},
onDragEnd: function(event, index) {
this.data.data[index].dragStatus = 0;
this.data.data[index].dragCurrent = false;
},
onDrop: function(event, index) {
if (event.stopPropagation) {
event.stopPropagation();
}
if (this.activeIndex !== index) {
this.data.data = this.array_move(this.data.data, this.activeIndex, index);
}
for (let index in this.data.data) {
if (!this.data.data.hasOwnProperty(index)) continue;
this.data.data[index].dragStatus = 0;
this.data.data[index].counter = 0;
this.data.data[index].dragCurrent = false;
}
return false;
},
array_move: function(arr, old_index, new_index) {
if (new_index >= arr.length) {
let k = new_index - arr.length + 1;
while (k--) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
return arr; // for testing
}
}
}
</script>
Edit 2
Figured it out! Using the loop index worked fine before, however this doesn't appear to be the case this time!
I changed the v-bind:key to use the database ID and this solved the issue!
There are some Caveats with arrays
Due to limitations in JavaScript, Vue cannot detect the following changes to an array:
When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
When you modify the length of the array, e.g. vm.items.length = newLength
To overcome caveat 1, both of the following will accomplish the same as vm.items[indexOfItem] = newValue, but will also trigger state updates in the reactivity system:
Vue.set(vm.items, indexOfItem, newValue)
Or in your case
randomise: function() {
let input = this.list;
for (let i = input.length-1; i >=0; i--) {
let randomIndex = Math.floor(Math.random()*(i+1));
let itemAtIndex = input[randomIndex];
Vue.set(input, randomIndex, input[i]);
Vue.set(input, i, itemAtIndex);
}
this.list = input;
}
Here is an working example: Randomize items fiddle
Basically I changed the logic of your randomize function to this:
randomize() {
let new_list = []
const old_list = [...this.list] //we don't need to copy, but just to be sure for any future update
while (new_list.length < 4) {
const new_item = old_list[this.get_random_number()]
const exists = new_list.findIndex(item => item.id === new_item.id)
if (!~exists) { //if the new item does not exists in the new randomize list add it
new_list.push(new_item)
}
}
this.list = new_list //update the old list with the new one
},
get_random_number() { //returns a random number from 0 to 3
return Math.floor(Math.random() * 4)
}
randomise: function() { let input = this.list;
for (let i = input.length-1; i >=0; i--) {
let randomIndex = Math.floor(Math.random()*(i+1));
let itemAtIndex = this.list[randomIndex];
Vue.set(this.list,randomIndex,this.list[i])
this.list[randomIndex] = this.list[i];
this.list[i] = itemAtIndex;
} this.list = input;
}
Array change detection is a bit tricky in Vue. Most of the in place
array methods are working as expected (i.e. doing a splice in your
$data.names array would work), but assigining values directly (i.e.
$data.names[0] = 'Joe') would not update the reactively rendered
components. Depending on how you process the server side results you
might need to think about these options described in the in vue
documentation: Array Change Detection.
Some ideas to explore:
using the v-bind:key="some_id" to have better using the push to add
new elements using Vue.set(example1.items, indexOfItem, newValue)
(also mentioned by Artokun)
Source
Note that it works but im busy so i cant optimize it, but its a little bit too complicted, i Edit it further tomorrow.
Since Vue.js has some caveats detecting array modification as other answers to this question highlight, you can just make a shallow copy of array before randomazing it:
randomise: function() {
// make shallow copy
let input = this.list.map(function(item) {
return item;
});
for (let i = input.length-1; i >=0; i--) {
let randomIndex = Math.floor(Math.random()*(i+1));
let itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
this.list = input;
}