- Replace Clerk with self-hosted JWT auth (register/login/verify, bcrypt passwords, Gmail OTP with console fallback) - Add lib/db.ts pg pool + transaction helpers; seed script migrates legacy Clerk-era schema (drop clerk_id, enforce UUID ids and unique email) - Add owner-gated admin API: stats, users, drivers CRUD, rides - Add dashboard/ Vite React owner dashboard (login, overview, users, fleet, rides) with dev-server proxy to avoid Expo CORS middleware - Add scripts/set-owner.mjs for role management
58 lines
1.5 KiB
TypeScript
58 lines
1.5 KiB
TypeScript
import { useState, useEffect, useCallback } from "react";
|
|
|
|
// Set by lib/session.tsx once a token is available; read synchronously here so
|
|
// callers never have to await SecureStore before every request.
|
|
let authToken: string | null = null;
|
|
|
|
export const setAuthToken = (token: string) => {
|
|
authToken = token;
|
|
};
|
|
|
|
export const clearAuthToken = () => {
|
|
authToken = null;
|
|
};
|
|
|
|
export const fetchAPI = async (url: string, options?: RequestInit) => {
|
|
try {
|
|
const headers = new Headers(options?.headers);
|
|
if (authToken && !headers.has("Authorization")) {
|
|
headers.set("Authorization", `Bearer ${authToken}`);
|
|
}
|
|
|
|
const response = await fetch(url, { ...options, headers });
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
}
|
|
return await response.json();
|
|
} catch (error) {
|
|
console.error("Fetch error:", error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
export const useFetch = <T>(url: string, options?: RequestInit) => {
|
|
const [data, setData] = useState<T | null>(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const fetchData = useCallback(async () => {
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const result = await fetchAPI(url, options);
|
|
setData(result.data);
|
|
} catch (err) {
|
|
setError((err as Error).message);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [url, options]);
|
|
|
|
useEffect(() => {
|
|
fetchData();
|
|
}, [fetchData]);
|
|
|
|
return { data, loading, error, refetch: fetchData };
|
|
};
|