UNPKG

@adonis-agora/authkit-react

Version:

Frontend ergonomics over AuthKit for AdonisJS + Inertia + React apps: a typed useAuth() hook, role-gating hooks and gating components.

49 lines (48 loc) 1.52 kB
import { useCallback, useEffect, useState } from 'react'; export async function jsonRequest(url, init = {}) { const { csrfToken, headers, ...rest } = init; const res = await fetch(url, { credentials: 'same-origin', headers: { Accept: 'application/json', ...(rest.body ? { 'Content-Type': 'application/json' } : {}), ...(csrfToken ? { 'X-CSRF-TOKEN': csrfToken } : {}), ...headers, }, ...rest, }); if (!res.ok) { let message = `Request failed (${res.status})`; try { const body = await res.json(); if (body && typeof body.message === 'string') message = body.message; } catch { } throw new Error(message); } const text = await res.text(); return (text ? JSON.parse(text) : null); } export function useResource(url, csrfToken) { const [state, setState] = useState({ data: null, loading: true, error: null, }); const refetch = useCallback(async () => { setState((s) => ({ ...s, loading: true, error: null })); try { const data = await jsonRequest(url, { csrfToken }); setState({ data, loading: false, error: null }); } catch (err) { setState({ data: null, loading: false, error: err }); } }, [url, csrfToken]); useEffect(() => { void refetch(); }, [refetch]); return { ...state, refetch }; }