'How to redirect to login page using service.js file of React app?
I have written this code:
export default class AuthService {
static getTwitterOauthToken() {
const url = `${apiUrl}/api/auth/getTwitterAuthToken?oauthCallback=${process.env.REACT_APP_TWITTER_CALLBACK_URL}`;
return axios.get(url).then((response) => response.data.token).catch(function (error) {
if(error.response.status===401){
//redirect to login page
}
});
}
}
Now, I have this auth service class for my functions. These functions are being called in my component. I need to catch errors in the API calls and if the calls return an error, I want to redirect my page to the login.
I don't know how to use react-router dom in service.js as it keeps showing errors. Please tell me how to redirect to the login page through the service.js file?
Solution 1:[1]
You have basically two valid options.
Pass the
historyobject to the utility function to be used.Take a passed
historyobject in thegetTwitterOauthTokenfunction.export default class AuthService { static getTwitterOauthToken(history) { // <-- history argument const url = " ..... "; return axios.get(url) .then((response) => response.data.token) .catch(function (error) { if (error.response.status === 401) { // redirect to login page history.replace("/login"); // <-- redirect } }); } }The caller must pass the
historyobject.const history = useHistory(); ... const token = await AuthService.getTwitterOauthToken(history);Create a global
historyobject that is importable.Create a custom history object matching the type of router used, i.e.
createBrowserHistoryfor aBrowserRouter,createHashHistoryfor aHashRouter, etc.import { createBrowserHistory } from "history"; const history = createBrowserHistory(); export default history;Use the low-level
Routerinstead of the high-level routers, and import the custom history object.import { Router } from 'react-router-dom'; import history from '../path/to/history'; ... <Router history={history}> <App /> </Router>Import the custom history object into the
AuthServicefile and use.import history from '../path/to/history'; // <-- global history imported export default class AuthService { static getTwitterOauthToken() { const url = " ..... "; return axios.get(url) .then((response) => response.data.token) .catch(function (error) { if (error.response.status === 401) { // redirect to login page history.replace("/login"); // <-- redirect } }); } }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Reese |
