Advertisement
MrB4RC0D3

http.ts

Apr 21st, 2024
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 1.75 KB | Source Code | 0 0
  1. import axios from "axios";
  2.  
  3. const API_URL = "http://localhost:8000/api";
  4.  
  5. export type LoginData = {
  6.     email: string;
  7.     password: string;
  8. };
  9.  
  10. export async function APILogin(formData: LoginData) {
  11.     try {
  12.         const { data } = await axios.post(
  13.             `${API_URL}/login`,
  14.             { email: formData.email, password: formData.password },
  15.             { withCredentials: true }
  16.         );
  17.         axios.defaults.headers.common["Authorization"] = `Bearer ${data.token}`;
  18.     } catch (err: any) {
  19.         if (err === null) throw new Error("Unrecoverable error!! Error is null!");
  20.  
  21.         if (axios.isAxiosError(err)) {
  22.             const response = err?.response;
  23.             const request = err?.request;
  24.  
  25.             if (err.code === "ERR_NETWORK") {
  26.                 console.log("Can't connect to the server...");
  27.                 //throw new Error("Can't connect to the server..."); // <-- Need to throw an error otherwise i can't use onError from my useMutation
  28.             } else if (err.code === "ERR_CANCELED") {
  29.                 console.log("The connection was canceled...");
  30.             }
  31.             if (response) {
  32.                 const statusCode = response?.status;
  33.  
  34.                 if (statusCode === 404) {
  35.                     console.log("The requested resource does not exist or has been deleted");
  36.                 } else if (statusCode === 401) {
  37.                     console.log("Please login to access this resource");
  38.                     //redirect user to login
  39.                 }
  40.             } else if (request) {
  41.                 //The request was made but no response was received, `error.request` is an instance of XMLHttpRequest in the browser
  42.             }
  43.         }
  44.  
  45.         console.log(err.message);
  46.     }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement