vuejs Pagination GET Url Params - vue.js

I am using https://github.com/gilbitron/laravel-vue-pagination pagination it works fine.I have included pagination in the page as below
<pagination :data="posts" #pagination-change-page="getResults"></pagination>
and the method
getResults(page = 1) {
axios.get('api/post?page=' + page)
.then(response => {
this.posts = response.data;
});
},
Now when i searchBy Category the pagination links shows api/findByCategoy?category=5&page=1
selectCatgory(e) {
axios.get('api/findByCategoy?category=' + e.target.value)
.then((data) => {
this.posts = data.data
})
.catch(() => {
})
},
I have inclded the GET params in the url . How to change the path in the getResults
public function searchByCategory(){
if ($search = \Request::get('category')) {
$posts = Post::where('category_id',$search)->orderBy('created_at','desc')->paginate(20);
$querystringArray = Input::only(['category']);
$posts->appends($querystringArray);
}else{
$posts = Post::latest()->paginate(10);
}
return $posts;
}

axios.get('api/findByCategoy?category=' + e.target.value + '&page=1')
https://en.wikipedia.org/wiki/Query_string

Related

vue method for loop wait for function complete

In this vue component, I have a method containing a for loop, calling another method. The second method does a request to the appserver. I need the first function waiting for the second to continue the for-loop. I've tried several async await options but doesn't understand how to implement it.
methods: {
selectFiles(files) {
this.progressInfos = [];
this.selectedFiles = files;
},
uploadFiles() {
this.message = "";
//var result = 0;
for (let i = 0; i < this.selectedFiles.length; i++) {
console.log(i)
//result = await this.upload(i, this.selectedFiles[i]);
this.upload(i, this.selectedFiles[i]);
}
},
upload(idx, file) {
this.progressInfos[idx] = { percentage: 0, fileName: file.name };
//console.log("FinDocuNum:" + financialDocument.finDocId)
FinancialDocumentDataService.upload(1, file, (event) => {
this.progressInfos[idx].percentage = Math.round(100 * event.loaded / event.total);
}).then((response) => {
let prevMessage = this.message ? this.message + "\n" : "";
this.message = prevMessage + response.status;
return 1;
}).catch(() => {
this.progressInfos[idx].percentage = 0;
this.message = "Could not upload the file:" + file.name;
return 0;
});
}
}
The upload function must be async and return a promise like this:
async upload(file) {
return new Promise((resolve, reject) => {
axios({url: url, data: file, method: 'POST'})
.then(resp => {
resolve(resp)
})
.catch(err => {
reject(err)
})
})
},

Wordpress Rest API: Return more than 100 results

I'm currently building a Vue webapp to display all custom post types, which recently exceeded 100 results. The Wordpress REST API limits the amount of posts to 100, and I'm unable to figure out how to paginate the requests so obtain all the posts on initial load.
My current code is as follows:
getPosts: function(context) {
return new Promise((resolve, reject) => {
if (context.state.posts) {
resolve();
} else {
axios
.get(
"https://localhost:81/admin/wp-json/wp/v2/cap?per_page=100"
)
.then(response => {
this.posts = response.data;
context.commit("storePosts", response.data);
console.log("Cap retrieved from Vuex!");
//console.log(this.posts);
resolve();
})
.catch(error => {
console.log(error);
reject(error);
});
}
});
}
I have the following computed code to display the results:
computed: {
caps() {
const caps = new Map();
if (this.$store.state.loading === false) {
sortPosts(this.$store.state.posts).forEach(post => {
const c = post.acf.address.country;
const s = post.acf.address.state;
if (!resorts.has(c)) resorts.set(c, new Map());
const stateMap = resorts.get(c);
if (!stateMap.has(s)) stateMap.set(s, []);
stateMap.get(s).push(post);
});
}
return caps;
}
}
How can I initiate loading all posts without user interaction?
Place this in API REST website to functions.php
add_filter( 'rest_{your_CPT}_collection_params', function ( $params, WP_Post_Type
$post_type ) {
if ( '{your_CPT}' === $post_type->name && isset( $params['per_page'] ) ) {
$params['per_page']['maximum'] = PHP_INT_MAX;
}
return $params;
}, 10, 2 );

Make a get request until a response comes from a request post vue js

I should upload file in my vue.js app. When I browse a file, I make post request and until I get a response, I need to make get request every 2 seconds for example. How can I do this?
uploadFile(event) {
this.isLoadingProcess = true;
console.log(this.isLoadingProcess);
let data = new FormData();
this.file = event.target.files[0];
data.append('name', 'uploaded-file');
data.append('file', event.target.files[0]);
const options = {
headers: {
'Content-Type': event.target.files[0].type,
},
onUploadProgress: function (progressEvent) {
const {loaded, total} = progressEvent;
let percentCompleted = Math.floor((loaded * 100) / total);
//console.log(percentCompleted);
if (percentCompleted !== 100) {
axios.get(url, {data: progressId})
.then(response => {
this.progress = response.data.progress;
// console.log(this.progress);
console.log(response.data.progress);
})
}
},
};
axios.post(
url,
data,
options
)
.then(response => {
console.log(response);
})
.finally(()=> {
this.isLoadingProcess = false;
})
what about this?
It asks api about update more than every 2 seconds, but It's better for my opinion in case, when endpoint isn't available
var processTimeoutFunction = null;
function checkProgress() {
axios.get('ckeck-process', ...).then(response => {
if (response.processIsActive) {
processTimeoutFunction = setTimeout(() => checkProgress(), 2000);
} else {
clearTimeout(processTimeoutFunction);
this.isLoadingProcess = false;
})
}

Doing multiple fetch not working React native

I'm doing a network scanner in react-native,
The problem is my api request are working but not in the for loop,
if I just made a for loop with 30loop its ok, but if I got more than 30loops
nothing is working.
if the IP to find is 192.168.1.79
and I set num_two to 60 and num_one to 1, this work good.
But if I set num_two to 50 and num_one to 1, this isn't working anymore.
My searching function:
searchInNetwork(net) {
return new Promise(async (resolve, reject) => {
for (let num_one = 1 ; num_one < 255 ; num_one++) {
let reseau = net + String(num_one);
for (let num_two = 50 ; num_two < 255 ; num_two++) {
let url = 'http://' + reseau + '.' + String(num_two) + ':3000/connect';
await ApiService.getRequest(url, 100)
.then((data) => {
console.log("SUCCESS");
ApiService.url = 'http://' + reseau + '.' + String(num_two) + ':3000';
ApiService.connected = true;
resolve();
})
` .catch((error) => {
if (url === "http://192.168.1.79:3000/connect")
console.log(error);
})
}
}
});
}
My ApiService class:
class ApiService {
static url = 'http://0.0.0.0:3000';
static connected = false;
static getUrl() {
return (this.url);
}
static getRequest(route, timeout) {
return new Promise(async (resolve, reject) => {
fetch(route)
.then((response) => response.json())
.then((responseJson) => {
ApiService.connected = true;
resolve(responseJson);
})
.catch((error) => {
ApiService.connected = false;
reject(error);
});
if (timeout) {
const error = new Error("Timeout net");
setTimeout(reject, timeout, error);
}
});
};
};
module.exports = ApiService;

Mutation for notifications in Vue.js

I have a store for notifications in my application. I can load all notifications and mark one notification as read. I wrote actions and mutations for each case. The last action is for marking all notifications as read but I am struggling with writing a mutation for this (commented part).
const actions = {
notifications(context) {
document.client
.get_notifications()
.then(ca => {
S_Helper.cmt_data(ca, "load_notifications", this);
})
.catch(error => {
ClientAlert.std_fail_with_err(error);
});
},
readNotification(id, params) {
document.client
.read_notification({ id, params })
.then(ca => {
if (ca.is_success()) {
context.commit("mark_notification", id);
} else {
ClientAlert.std_fail();
}
})
.catch(error => {
ClientAlert.std_fail_with_err(error);
});
},
readAllNotifications(context, params) {
params = params || {};
document.client
.read_all_notifications(params)
.then(ca => {
if (ca.is_success()) {
context.commit("mark_all_notifications", this);
} else {
ClientAlert.std_fail();
}
})
.catch(error => {
ClientAlert.std_fail_with_err(error);
});
}
};
const mutations = {
load_notifications(context, data) {
context.notifications = data;
},
mark_notification(state, id) {
let new_data = state.notifications.map(function(element) {
if (!!element.id && element.id === id) {
element.viewed = true;
}
return element;
});
state.notifications = new_data;
}
//mark_all_notifications(context, data) {
//}
};
mark_all_notifications(state, data) {
state.notifications = state.notifications.map(notification => {
notification.viewed = true
return notification
})
}
A simple map should work.