For Edon

mail@pastecode.io avatar
unknown
javascript
5 months ago
3.9 kB
3
Indexable
import { createContext, useEffect, useState } from "react";
import { UserProfile } from "../models/user";
import { useNavigate } from "react-router-dom";
import { loginAPI, registerAPI } from "../services/AuthService";
import { toast } from "react-toastify";
import React from "react";
import axios from "axios";

type UserContextType = {
  user: UserProfile | null;
  token: string | null;
  refreshToken: string | null;
  registerUser: (email: string, username: string, password: string) => void;
  loginUser: (email: string, password: string) => void;
  logout: () => void;
  isLoggedIn: () => boolean;
};

type Props = { children: React.ReactNode };

const UserContext = createContext<UserContextType>({} as UserContextType);

export const UserProvider = ({ children }: Props) => {
  const navigate = useNavigate();
  const [token, setToken] = useState<string | null>(null);
  const [refreshToken, setRefreshToken] = useState<string | null>(null);
  const [user, setUser] = useState<UserProfile | null>(null);
  const [isReady, setIsReady] = useState(false);

  useEffect(() => {
    const user = localStorage.getItem("user");
    const token = localStorage.getItem("token");
    const refreshToken = localStorage.getItem("refreshToken");
    if (user && token) {
      setUser(JSON.parse(user));
      setToken(token);
      setRefreshToken(refreshToken);
      axios.defaults.headers.common["Authorization"] = "Bearer " + token;
    }
    setIsReady(true);
  }, []);

  const registerUser = async (
    email: string,
    username: string,
    password: string
  ) => {
    await registerAPI(email, username, password)
      .then((res) => {
        if (res) {
          localStorage.setItem("token", res?.data.token.token);
          localStorage.setItem("refreshToken", res?.data.refreshToken.token);
          const userObj = {
<<<<<<< HEAD
            userId: res?.data.userId,
=======
>>>>>>> fcceed0158a98313357a73e258b685f454bf9a61
            companyId: res?.data.companyId,
            displayName: res?.data.displayName,
            email: res?.data.email,
            role: res?.data.role
          };
          localStorage.setItem("user", JSON.stringify(userObj));
          setToken(res?.data.token.token!);
          setToken(res?.data.refreshToken.token!);
          setUser(userObj!);
          toast.success("Login Success!");
          navigate("/dashboard");
        }
      })
      .catch((e) => toast.error("Server error occured"));
  };

  const loginUser = async (email: string, password: string) => {
    await loginAPI(email, password)
      .then((res) => {
        if (res) {
          localStorage.setItem("token", res?.data.token.token);
          localStorage.setItem("refreshToken", res?.data.refreshToken.token);
          const userObj = {
            userId: res?.data.userId,
            companyId: res?.data.companyId,
            displayName: res?.data.displayName,
            email: res?.data.email,
            role: res?.data.role
          };
          localStorage.setItem("user", JSON.stringify(userObj));
          setToken(res?.data.token.token!);
          setRefreshToken(res?.data.refreshToken.token!);
          setUser(userObj!);
          toast.success("Login Success!");
          navigate("/dashboards/sales");
        }
      })
      .catch((e) => toast.error("Server error occured"));
  };

  const isLoggedIn = () => {
    return !!user;
  };

  const logout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("refreshToken");
    localStorage.removeItem("user");
    setUser(null);
    setRefreshToken("")
    setToken("");
    navigate("/login");
  };

  return (
    <UserContext.Provider
      value={{ loginUser, user, token, refreshToken, logout, isLoggedIn, registerUser }}
    >
      {isReady ? children : null}
    </UserContext.Provider>
  );
};

export const useAuth = () => React.useContext(UserContext);
Leave a Comment