Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import axios from "axios";
- const API_URL = "http://localhost:8000/api";
- export type LoginData = {
- email: string;
- password: string;
- };
- export async function APILogin(formData: LoginData) {
- try {
- const { data } = await axios.post(
- `${API_URL}/login`,
- { email: formData.email, password: formData.password },
- { withCredentials: true }
- );
- axios.defaults.headers.common["Authorization"] = `Bearer ${data.token}`;
- } catch (err: any) {
- if (err === null) throw new Error("Unrecoverable error!! Error is null!");
- if (axios.isAxiosError(err)) {
- const response = err?.response;
- const request = err?.request;
- if (err.code === "ERR_NETWORK") {
- console.log("Can't connect to the server...");
- //throw new Error("Can't connect to the server..."); // <-- Need to throw an error otherwise i can't use onError from my useMutation
- } else if (err.code === "ERR_CANCELED") {
- console.log("The connection was canceled...");
- }
- if (response) {
- const statusCode = response?.status;
- if (statusCode === 404) {
- console.log("The requested resource does not exist or has been deleted");
- } else if (statusCode === 401) {
- console.log("Please login to access this resource");
- //redirect user to login
- }
- } else if (request) {
- //The request was made but no response was received, `error.request` is an instance of XMLHttpRequest in the browser
- }
- }
- console.log(err.message);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement