Self-hosted dashboard and admin auth (#4837)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
This commit is contained in:
co-authored by
kartik-mem0
parent
15feaa8ac4
commit
db8ac61713
@@ -0,0 +1,56 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { toast } from "@/components/ui/use-toast";
|
||||
import { getErrorMessage } from "@/lib/error-message";
|
||||
|
||||
interface UseApiQueryOptions<T> {
|
||||
enabled?: boolean;
|
||||
errorToast?: string;
|
||||
initialData?: T;
|
||||
}
|
||||
|
||||
interface UseApiQueryResult<T> {
|
||||
data: T | undefined;
|
||||
isLoading: boolean;
|
||||
error: string;
|
||||
refetch: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function useApiQuery<T>(
|
||||
fetcher: () => Promise<T>,
|
||||
options: UseApiQueryOptions<T> = {},
|
||||
): UseApiQueryResult<T> {
|
||||
const { enabled = true, errorToast, initialData } = options;
|
||||
|
||||
const [data, setData] = useState<T | undefined>(initialData);
|
||||
const [isLoading, setIsLoading] = useState(enabled);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const fetcherRef = useRef(fetcher);
|
||||
fetcherRef.current = fetcher;
|
||||
|
||||
const run = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
setData(await fetcherRef.current());
|
||||
} catch (err) {
|
||||
const message = getErrorMessage(err, errorToast || "Request failed");
|
||||
setError(message);
|
||||
if (errorToast) {
|
||||
toast({
|
||||
title: errorToast,
|
||||
description: message,
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [errorToast]);
|
||||
|
||||
useEffect(() => {
|
||||
if (enabled) void run();
|
||||
}, [enabled, run]);
|
||||
|
||||
return { data, isLoading, error, refetch: run };
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useContext } from "react";
|
||||
import { AuthContext } from "@/lib/auth";
|
||||
|
||||
export function useAuth() {
|
||||
return useContext(AuthContext);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
function useDebounce<T>(value: T, delay = 500): T {
|
||||
const [debouncedValue, setDebouncedValue] = useState<T>(value);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedValue(value);
|
||||
}, delay);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [value, delay]);
|
||||
|
||||
return debouncedValue;
|
||||
}
|
||||
|
||||
export default useDebounce;
|
||||
Reference in New Issue
Block a user