Vue error for pagination: response is not defined - ajax

I keep getting this Vue error: "ReferenceError: response is not defined" but when I check in the console, the data is all there.
I intend to use the data from the response to make pagination. Thanks in advance.
Methods
getAllUserData(){
let $this=this;
axios.get('api/members/getAllMembersData').then(response=>this.members=response.data.data);
$this.makePagination(response.meta,response.links);
},
makePagination(meta,links){
let pagination={
current_page:meta.current_page,
last_page:meta.last_page,
next_page_url:links.next,
prev_page_url:links.prev
}
this.pagination = pagination;
}

axios.get() is an async function. The code that follows this function will not be executed after the ajax request completes, but long before that. Because of this, the variable response does not exist yet.
All code that has to be executed when the ajax call completes has to be put in the .then() function of the call.
getAllUserData(){
axios.get('api/members/getAllMembersData').then(response => {
this.members = response.data.data;
this.makePagination(response.data.meta, response.data.links);
});
},

Your response is still inside the axios get method, therefore the makePagination function has to be called inside axios method as well (inside .then())
getAllUserData(){
let $this=this;
axios.get('api/members/getAllMembersData').then(response=>
this.members=response.data.data
$this.makePagination(response.data.meta,response.data.links);
},
makePagination(meta,links){
let pagination={
current_page:meta.current_page,
last_page:meta.last_page,
next_page_url:links.next,
prev_page_url:links.prev
}
this.pagination = pagination;
}

Related

How do I get a specific column name values using Axios Promise-based Http Request in Vue.js and Laravel 8

If I do this in my Vue.js script component
getResumeAPIData(id){
// declare a response interceptor
axios.interceptors.response.use((response) => {
// do something with the response data
console.log('Response was received');
return response;
}, error => {
// handle the response error
return Promise.reject(error);
});
// sent a GET request
axios.get(`api/resume-data-returns/${id}`)
.then((response)=>{
this.RelationTable = response.data
console.log(this.RelationTable);
})
},
I get a response like this
{"id":1,"name":"userlocalvm","email":"userlocalvm#v","email_verified_at":null,"type":"user","bio":"Why","photo":"1606931001.jpeg","created_at":"2020-12-02T16:01:00.000000Z","updated_at":"2020-12-02T17:43:21.000000Z"}
Because of my Laravel api.php->Controller Backend code
$findOrFailId = Resumes::findOrFail($forEachId);
$foreignKeyOfResTable = $findOrFailId->user_id;
return User::findOrFail($foreignKeyOfResTable);
But if I do it like this as
// sent a GET request
axios.get(`api/resume-data-returns/${id}`)
.then((response)=>{
this.RelationTable = response.data.created_at
console.log(this.RelationTable);
})
The added dot then the property name of the column
response.data.created_at
I get a response
undefined
Sorry if this is a silly question as I am still quite a rookie in programming in general and the jargons that comes with it and I want learn and master javascript and php so bad!
It might be that the response is inside another data object. You might have to do something like this:
response.data.data.created_at

Load() doesn't seems to run when I set initial files

I am struggling to set up initial files. I have tried both pond.addFile() and files: {} in filePond options, but both of them return 400 Can't load URL.
I have checked my console, but I cannot find the related XHR request or the corresponding console.log() I wrote in my custom load() function. My guess is load() never fired. What could go wrong here?
My load function:
load: (source, load, error, progress, abort, headers) => {
var myRequest = new Request(source);
console.log('Load function running');
console.log(source);
fetch(myRequest).then(function(response) {
response.blob().then(function(myBlob) {
load(myBlob)
});
});
}

Cannot return the value from a function in AJAX

Hi I cannot return the value from the function. It's returns undefined. And I don't know why. Below is the code.
function getData() {
axios.get('/task')
.then(response => {
return response.data.tasks;
});
}
//calls the function
getData();
But when i call the function getTaskData, it returns only undefined.
Please help. Thanks.
You're dealing with Promises in this case. They do not behave like a typical function in JavaScript. I would recommend starting with some basics:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
As to your question, getData does not return anything, nor is there a getTaskData in the code you've provided.
As said in the previews response you’re dealing with promise,
You need to wait finishing you’re Ajax request and then you deal with response,
In your code you can do like this
async function getData() {
const response = await axios.get('/task')
return response
}
Call function with callback for the success and failure cases of the Promise
getData()
.then(response => {
console.log(response.data.tasks)
})
.catch(error => {
console.log("ERROR")
})

Axios Reponse Interceptor : unable to handle an expired refresh_token (401)

I have the following interceptor on my axios reponse :
window.axios.interceptors.response.use(
response => {
return response;
},
error => {
let errorResponse = error.response;
if (errorResponse.status === 401 && errorResponse.config && !errorResponse.config.__isRetryRequest) {
return this._getAuthToken()
.then(response => {
this.setToken(response.data.access_token, response.data.refresh_token);
errorResponse.config.__isRetryRequest = true;
errorResponse.config.headers['Authorization'] = 'Bearer ' + response.data.access_token;
return window.axios(errorResponse.config);
}).catch(error => {
return Promise.reject(error);
});
}
return Promise.reject(error);
}
);
The _getAuthToken method is :
_getAuthToken() {
if (!this.authTokenRequest) {
this.authTokenRequest = window.axios.post('/api/refresh_token', {
'refresh_token': localStorage.getItem('refresh_token')
});
this.authTokenRequest.then(response => {
this.authTokenRequest = null;
}).catch(error => {
this.authTokenRequest = null;
});
}
return this.authTokenRequest;
}
The code is heavily inspired by https://github.com/axios/axios/issues/266#issuecomment-335420598.
Summary : when the user makes a call to the API and if his access_token has expired (a 401 code is returned by the API) the app calls the /api/refresh_token endpoint to get a new access_token. If the refresh_token is still valid when making this call, everything works fine : I get a new access_token and a new refresh_token and the initial API call requested by the user is made again and returned correctly.
The problem occurs when the refresh_token has also expired.
In that case, the call to /api/refresh_token returns a 401 and nothing happens. I tried several things but I'm unable to detect that in order to redirect the user to the login page of the app.
I found that in that case the if (!this.authTokenRequest) statement inside the _getAuthToken method returns a pending Promise that is never resolved. I don't understand why this is a Promise. In my opinion it should be null...
I'm a newbie with Promises so I may be missing something !
Thanks for any help !
EDIT :
I may have found a way much simpler to handle this : use axios.interceptors.response.eject() to disable the interceptor when I call the /api/refresh_token endpoint, and re-enable it after.
The code :
createAxiosResponseInterceptor() {
this.axiosResponseInterceptor = window.axios.interceptors.response.use(
response => {
return response;
},
error => {
let errorResponse = error.response;
if (errorResponse.status === 401) {
window.axios.interceptors.response.eject(this.axiosResponseInterceptor);
return window.axios.post('/api/refresh_token', {
'refresh_token': this._getToken('refresh_token')
}).then(response => {
this.setToken(response.data.access_token, response.data.refresh_token);
errorResponse.config.headers['Authorization'] = 'Bearer ' + response.data.access_token;
this.createAxiosResponseInterceptor();
return window.axios(errorResponse.config);
}).catch(error => {
this.destroyToken();
this.createAxiosResponseInterceptor();
this.router.push('/login');
return Promise.reject(error);
});
}
return Promise.reject(error);
}
);
},
Does it looks good or bad ? Any advice or comment appreciated.
Your last solution looks not bad. I would come up with the similar implementation as you if I were in the same situation.
I found that in that case the if (!this.authTokenRequest) statement inside the _getAuthToken method returns a pending Promise that is never resolved. I don't understand why this is a Promise. In my opinion it should be null...
That's because this.authTokenRequest in the code was just assigned the Promise created from window.axios.post. Promise is an object handling kind of lazy evaluation, so the process you implement in then is not executed until the Promise was resolved.
JavaScript provides us with Promise object as kind of asynchronous event handlers which enables us to implement process as then chain which is going to be executed in respond with the result of asynchronous result. HTTP requests are always inpredictable, because HTTP request sometimes consumes much more time we expect, and also sometimes not. Promise is always used when we use HTTP request in order to handle the asynchronous response of it with event handlers.
In ES2015 syntax, you can implement functions with async/await syntax to hanle Promise objects as it looks synchronous.

Wait for an ajax request to complete in React?

Below is my react code I want that firstly the ajax code should execute then the rest of the code should execute.
expected output in console:
inside ajax
outside ajax
current output in console :
outside ajax
inside ajax
import React from 'react';
import request from 'superagent'
const UserItems = () => {
request.get('http://localhost:4000/user/1/items.json')
.then((res, err) => {
if (err) {
console.log("errror found")
}
var data = JSON.parse(res.text)
console.log("inside ajax")
console.log(data)
})
console.log("outside ajax")
console.log(data)
};
export default UserItems;
Any suggestion !!!
As hainguyen points out, ajax is typically asynchronous so the code afterwards will run until the request is complete, at which time the inner function is executed. So the outer console logs will almost certainly run first in your code. While there are ways around this as hainguyen points out, most recommend against it. Ajax is something which takes time, and therefore your code structure should reflect that. If you ever find yourself wanting to run code while the ajax request is in process, you might dislike a synchronous structure. My "I wait for no one" log shows the power of an asynchronous approach since that logic will run quickly while you would normally be waiting on the request without being able to do anything.
Rather than make it synchronous why not use functions to handle the asynchronous behavior better like wrapping whatever you want to run after the inside console log in a function: (I called it outside()) This will output "inside ajax", "outside ajax". This way you can create dependencies on your ajax return and still have the option for running stuff in the meantime.
import React from 'react';
import request from 'superagent';
const UserItems = () => {
request.get('http://localhost:4000/user/1/items.json')
.then((res, err) => {
if (err) {
console.log("errror found");
}
var data = JSON.parse(res.text);
console.log("inside ajax");
console.log(data);
outside();
});
function outside(){
console.log("outside ajax");
console.log(data);
}
console.log("I wait for no one, run me as quick as possible!");
};
export default UserItems;
I don't know about request library but ajax is async by default. If you want ajax perform sync request, you should do something like this:
function getRemote() {
return $.ajax({
type: "GET",
url: remote_url,
async: false
}).responseText;
}
Important line: async: false

Resources