55 lines
1.4 KiB
TypeScript
55 lines
1.4 KiB
TypeScript
'use client';
|
|
|
|
import { useState, useEffect } from 'react';
|
|
import { OperatorSession } from './types';
|
|
|
|
export function useOpsSession(initialSession?: OperatorSession | null) {
|
|
const [session, setSession] = useState<OperatorSession | null>(initialSession ?? null);
|
|
const [isLoading, setIsLoading] = useState<boolean>(!initialSession);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (initialSession) {
|
|
setSession(initialSession);
|
|
setIsLoading(false);
|
|
return;
|
|
}
|
|
|
|
let isMounted = true;
|
|
async function fetchSession() {
|
|
try {
|
|
const res = await fetch('/api/ops/session', {
|
|
headers: { accept: 'application/json' },
|
|
cache: 'no-store',
|
|
});
|
|
if (!res.ok) {
|
|
if (isMounted) {
|
|
setError('Failed to fetch Operations session.');
|
|
setIsLoading(false);
|
|
}
|
|
return;
|
|
}
|
|
const data = await res.json();
|
|
if (isMounted) {
|
|
if (data?.session) {
|
|
setSession(data.session);
|
|
}
|
|
setIsLoading(false);
|
|
}
|
|
} catch {
|
|
if (isMounted) {
|
|
setError('Unable to connect to Operations platform.');
|
|
setIsLoading(false);
|
|
}
|
|
}
|
|
}
|
|
|
|
void fetchSession();
|
|
return () => {
|
|
isMounted = false;
|
|
};
|
|
}, [initialSession]);
|
|
|
|
return { session, isLoading, error };
|
|
}
|