mirror of
https://github.com/steveiliop56/tinyauth.git
synced 2025-11-03 15:45:51 +00:00
Initial Commit
This commit is contained in:
42
site/src/context/user-context.tsx
Normal file
42
site/src/context/user-context.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import React, { createContext, useContext } from "react";
|
||||
import { UserContextSchemaType } from "../schemas/user-context-schema";
|
||||
import axios from "axios";
|
||||
|
||||
const UserContext = createContext<UserContextSchemaType | null>(null);
|
||||
|
||||
export const UserContextProvider = ({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
const {
|
||||
data: userContext,
|
||||
isLoading,
|
||||
error,
|
||||
} = useQuery({
|
||||
queryKey: ["isLoggedIn"],
|
||||
queryFn: async () => {
|
||||
const res = await axios.get("/api/status");
|
||||
return res.data;
|
||||
},
|
||||
});
|
||||
|
||||
if (error && !isLoading) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return (
|
||||
<UserContext.Provider value={userContext}>{children}</UserContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useUserContext = () => {
|
||||
const context = useContext(UserContext);
|
||||
|
||||
if (context === null) {
|
||||
throw new Error("useUserContext must be used within a UserContextProvider");
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user