From 6a5b01bf0c490d78e0134f7fc64975af2f3f7071 Mon Sep 17 00:00:00 2001 From: Antony Kurniawan Date: Wed, 1 Oct 2025 11:02:59 +0700 Subject: [PATCH] add: auth context --- src/context/AuthContext.jsx | 42 +++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/context/AuthContext.jsx diff --git a/src/context/AuthContext.jsx b/src/context/AuthContext.jsx new file mode 100644 index 0000000..fb4d9b5 --- /dev/null +++ b/src/context/AuthContext.jsx @@ -0,0 +1,42 @@ +import { createContext, useContext, useState, useEffect } from "react"; +import { SendRequest } from "../utils/api"; + +const AuthContext = createContext(); + +export const AuthProvider = ({ children }) => { + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); + + // fetch user info saat mount + useEffect(() => { + const fetchUser = async () => { + try { + const res = await SendRequest({ prefix: "/auth/me", method: "GET" }); + setUser(res); + } catch (err) { + setUser(null); + } finally { + setLoading(false); + } + }; + fetchUser(); + }, []); + + const login = (accessToken) => { + localStorage.setItem("token", accessToken); + }; + + const logout = () => { + localStorage.clear(); + setUser(null); + window.location.href = "/signin"; + }; + + return ( + + {children} + + ); +}; + +export const useAuth = () => useContext(AuthContext);