So I have an issue on local When I make a request I get the data, on Dev/QA/Prod nothing comes back I checked the network dev tools on my browser and I see that the request is being cancelled
So this happens when you return/reload window before the call finishes (the API call made is still being processed and has not completed).
onRemove = (evt) => {
evt.preventDefault();
evt.stopPropagation();
this.props.onRemove(this.props.item);
window.location.reload(); // this will cancel the call and your request wont
//be execute.
}
Removing this will sort the issue ->
" window.location.reload();"
The best thing to do is to make sure that you wait for the request to be processed before you do any other thing.
onRemove = (evt) => {
evt.preventDefault();
evt.stopPropagation();
this.props.onRemove(this.props.item);
}
Related
I've to make 3 back-end api-call before showing the UI screen. So, I used the ion-loading below snippet,
I'm presenting the loader in 1st backend call and it get closed in the first call itself. But I've to close the loader in third api call to show the screen.
How to extend the loader till the last api call,
this.presentLoading();
async presentLoading() {
this.loading = await this.loadingController.create({
spinner: null,
cssClass: 'custom-class custom-loading',
});
await this.loading.present();
}
One way to accomplish this would be to call .then() on loadingController.create() and then process all your api calls inside there. Here's how I would organize it so that your loading controller is dismissed properly either when the 3 api calls succeed or when one of them fails. This setup assumes your api call functions return promises.
this.loadingController.create({
message: 'Loading, please wait...'
}).then((loading) => {
loading.present();
Promise.all([apiCallOne(), apiCallTwo(), apiCallThree()])
.catch((err) => {
console.log(err);
loading.dismiss();
})
.then((results) => {
// do something with results ...
loading.dismiss();
});
});
I have a simple React component, a button and a function which calls an API endpoint. When I click the button the API inside event gets called twice. I have read many posts here on stackoverflow and tried all of them but still have same issues.
Moreover, even though I can see 2 records in db for each call, in the Google Dev tools shows only 1 xhr call which is wired.
I have already tried to pass function reference instead of function itself and even called function via () => { } but same result.
<button type="button" onClick={ this.onSubmitForm }>Save</button>
onSubmitForm = (e) => {
// e.preventDefault();
const response = axios.post('http://localhost/util/index.php/api/record', {name: 'test'} );
console.log(response) // Even this line is logged once in console ;
}
Neither your react app nor the API, it is the browser itself. Have a look at this https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
A preflight request to let the server know what HTTP method will be used when the actual request is made.
If in the Google Dev tools shows only 1 xhr call. Then it's not a front-end problem. It might be something wrong with the api function in server side. Maybe it calls the insert query twice.
In React, I am trying to set a variable to an axios call after I return the data.
But, when console logging the variable afterwards, it's a Promise.
How do I get the value from the promise and set it to the variable?
let fourPackProducts = axios.get('URL').then(response => {
return response.data })
console.log(fourPackProducts)
Console log screenshot
You did exactly what you are asking to do. If you want to console.log the correct data, chain another then like so,
let promiseResponse = axios.get('URL')
.then(response => response.data)
.then( data => { console.log( data ); return data });
Remember, ajax requests are async, so code after an ajax request not using async handlers will run, the compiler does not stop and wait for the request to complete
You're console logging a promise because fourPackProducts is a promise. Another part of the issue is that since the promise is asynchronous, the console log is being called before the promise response comes through. To properly set the promise response to a variable, try the following:
let promiseResponse;
let fourPackProducts = axios.get('URL').then(response => {
promiseResponse = response.data;
console.log(promiseResponse);
return promiseResponse;
})
Presumably you want to do something with this variable afterward, but if the promise is not yet completed then the variable will be undefined. In order to use the variable after it has been set to the promise response, you will need to chain promises.
fetch() is a great improvement over the classic XMLhttpRequest() However I was wondering if I add window.addEventListener('unhandledrejection', event => ยทยทยท); to my index.android.js and index.ios.js could I theoretically remove all of my .catch() from my promise chains and make a pseudo global promise rejection handler? I am building a react native app that relies heavily on api calls, many of which are authenticated with user tokens. When a user logs in a token is stored in asynchronous storage, but each token will expire after a certain amount of time. if a user opens the app and unwittingly attempts to make a call that requires authentication with an expired token I would like the user to be routed to the login page regardless of what call was made, or what component the call is in. I currently have each individual promise chain handling unauthenticated calls on their own. Is there a better way to do it?
You could make a custom abstraction on top of fetch, which will provide a way of communicating with API and also have some business logic, which for you case is to request an auth token or make a redirect. Then you use this abstraction in the rest of the code to make API calls. Here is a small example to demonstrate the idea:
export default function request(url, options = {}) {
const req = fetch(url)
.then((response) => {
// Global response handler
// ...
// Hand response down the promise chain
return response;
})
.catch((err) => {
// Global error handler
// Check error status and (make redirect/request auth token)
// Throw error down the promise chain if needed
throw err;
});
// Returns a promise
return req;
}
Then you use it in your code like fetch(), but instead you'll be able to modify and extend it for you needs any time.
request('http://example.com/api/post/1')
.then((response) => {
// "response" has whatever you returned from global handler
})
.catch((err) => {
// "err" is whatever you've thrown from global handler
});
I have a form that upon submit will POST a message to our REST API.
If successful, the REST API will return the updated value in the same JSON format as the GET call makes.
For some reason, even after the POST call has finished, the {{escalation.policy}} is still not updated in the scope.
var escalation = Escalation.save({
policy: $scope.policy,
}).$promise.then(function (data) {
$scope.escalation.push(data);
alert(data);
},
Is your REST request coming in then function? Try to put error function next to then() and make sure your request is successfully executed and responded back.
You need to call $scope.$apply() after $scope.escalation.push(data);. That will cause a new $digest to occur forcing the view to update, my guess is that $promise.then is ocurring outside the usual digest loop.
This is the current full segment of code for the submit()
$scope.submit = function () {
var Escalation = $resource('/api/escalation');
var escalation = Escalation.save({
policy: $scope.policy,
}).$promise.then(function (data) {
$scope.escalation.push(data);
}, function (error) {
alert('This request could not be processed. Please try again later.');
console.log(error);
});
};
The API will always return in the following format for a GET or POST:
{"policy":"Whatever the current/new policy is."}
Alas, i can still not seam to figure out why the view will not update.