score:0
You need to create a function which handles that you have a proper request sender. This is a promisified request sender:
function makeRequest (method, url, succ, err) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
succ(response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
err(response);
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
err(xhr.statusText);
};
xhr.send();
});
}
// Example:
makeRequest('GET', 'http://example.com')
.then(function (datums) {
console.log(datums);
})
.catch(function (err) {
console.error('Augh, there was an error!', err.statusText);
});
Source: How do I promisify native XHR?
Now, let's create a function which awaits that promise:
async function syncedRequest(method, url, succ, err) {
await makeRequest(method, url, succ, err);
}
Implement success and error callbacks:
function successTokenCallback(response) {
this.token = response;
}
function errorTokenCallback(message) {
console.log(message);
}
and a token refresher:
function refreshToken(value) {
syncedRequest(method, url, successTokenCallback, errorTokenCallback);
//do something with successTokenCallback.token
return value;
}
and you can do this wherever you want a token refresh to happen before the return:
return refreshToken(value);
The problem I see with this is that you are making your requests synchronous, which is in general an anti-pattern. You should aim to avoid blocking your Javascript flow because you wait for a request whenever possible. However, if it is absolutely necessary, you can do the above.
Source: stackoverflow.com
Related Query
- Authenticating routes by doing a quick check from the database
- "Rendered more hooks than during the previous render" error when the initial value for the hook is a query result from a database
- How can I redirect from wildcard routes to the home page?
- How to retrieve the last added record from the database in the MERN technology stack?
- React Native - Stack Navigator Check from which screen has the new panel been opened
- Conditionally check value from context and then navigate after login in the same function call in React
- How to fix the state update in react while getting data from firestore database
- How to dynamically get the images from database into react carousel?
- How to check the response from global fetch in JEST test case
- How can I get the right data from database with react
- In React, which value should I rely on when doing a fetch in a dropdown? the e.target value or the value from the state
- What is the proper way to get data from database in react?
- How to fetch all the documents with unique id from firestore database using React?
- How to display only the data from a detail component using nested routes in React?
- How to display HTML tags in React fetched from the database
- Remove items from the database on leaving or closing the page from a React Component
- Refreshing the state from the database only if there is a change in the database in react redux application
- How can I update the value from the database in React
- How to check whether the email from a input field exists in the below list or not?
- Starting a php session from react with an axios call does not keep the session alive, but doing it with postman works just fine
- How can I check if login is successful, then display the protected routes in react hooks
- Trying to load the gltf link from the mongodb database in react three fiber
- How can i programmatically check a radio button after i read the value from localStorage
- Change the enum index value from database in javascript file [Laravel]
- In React, how do I retrieve information from the database after Authentication but before Authorization?
- Uploading audio files to Firebase Cloud Database and then redering it from the Database to React js + Endless loop issue
- React with firebase cloud firestore- presenting data from the database
- How to create routes from anchor tags from react router without the # in the url
- I want to send the data from a request form to a database in the MySQL workbench from a javascript file in a ReactJs project, but I have no idea how
- Firebase with React - unable to delete items from the database
More Query from same tag
- Sequelize JOIN query is throwing below error for the get request
- Socket.io and Node/Express - Maximum call stack size exceeded
- Rendering React components with promises inside the render method
- In React Router, how do i remove / change the param in history.push that i have sent before?
- Double tap to make change on checkbox Safari
- How can I get flex items positioned within a grid element aligned to the center
- react load local storage at first
- Selenium (python) testing a React-js frontend leads to stale error message when trying to input text into input field
- NPM - Failed to replace env in config: ${NPM_TOKEN}
- Importing CSS in Semantic-UI-React
- react app, load components based on dropdown option
- Implementing multiple routing in React
- How create a link from a parameter in React component?
- how to pass in a value from child to parent class in react js
- Convert json data in reactjs
- Adding text into a text input onKeyPress react.js
- Preflight Doesn't Pass Control Check Access-Control-Allow-Origin Not Present
- Why is my custom React-leaflet marker not displaying on my map?
- React unit test getting TypeError: Cannot read properties of undefined (reading 'Component')
- How to organise components for a single page scrolling website in React?
- Did not work react router in nested
- how can I reuse the function to update different parts of the state of a React component?
- Ignore previous asynchronous call and execute the latest
- Error validation with Material UI Autcomplete & React hook form
- React - What is the Best Way to use Multiple createContexts?
- How to highlight the current month?
- I want to pass two functions in onChange attribute in id password in input field. I want to pass event also and confirm() function also. (ReactJs)
- How to display the image and background image from the array in react
- Why sidebar not sticky or fixed in left and right side in React.js?
- Stuck with webpack HMR configuration