This is my component that represents the Login page
import { HttpService } from 'src/assets/js/httpservice';
// ** omissis other imports **
export default class PrivatePage extends React.Component {
constructor(props) {
super(props);
}
public render() {
return (
<div>
<ul>
<li>
<InputText name="Text" id="Text" />
</li>
<li>
<InputText name="Email" id="Email" />
</li>
<li>
<Button onClick={this.send} label="Send ticket" />
</li>
</ul>
</div>
)
}
private send() {
HttpService.post(PATH.sendTicket, this.state.ticketModel).then(data => {
if (data.ErrorCode === 0) {
this.setState({
sentSuccessfull: true
});
}
else {
// show an error popup
}
});
}
}
When the "Send ticket" button is pressed, it calls the HttpService.post
method to make an API call to send a ticket to the system. As you can see in the import section, the HttpService is hosted on an external JS file. This is the code of the HttpService.post
method.
public static async post(path, body) {
return window.fetch(path, {
body: JSON.stringify(body),
cache: "no-cache",
method: "post"
})
.then(data => {
// call successfull
})
.catch(data => {
if (data.status === 401) {
// REDIRECT HERE
}
else {
return data.json();
}
});
}
Now, if the API call fails because the user is not authenticated (HTTP status 401 is returned), I need to redirect the user to the Login page. I would avoid to handle the 401 HTTP status in every component, so I prefer that the redirect is made directly inside the HttpService.post
method.