2024-09-08 10:42:34 -05:00
|
|
|
import {
|
|
|
|
|
unwrapBlitzkitResponse,
|
2024-10-05 16:44:07 -05:00
|
|
|
type BlitzkitResponse,
|
|
|
|
|
type TankVotes,
|
2024-09-08 10:46:12 -05:00
|
|
|
} from '@blitzkit/core';
|
2024-09-01 17:41:50 -05:00
|
|
|
import { useEffect, useState } from 'react';
|
2024-10-09 21:04:49 -05:00
|
|
|
import { App } from '../stores/app';
|
2024-09-01 15:46:39 -05:00
|
|
|
|
|
|
|
|
const cache: Record<string, Promise<TankVotes> | TankVotes> = {};
|
|
|
|
|
|
|
|
|
|
export function useTankVotes(id: number) {
|
2024-09-01 17:41:50 -05:00
|
|
|
const [votes, setVotes] = useState<TankVotes | null>(null);
|
2024-10-09 21:04:49 -05:00
|
|
|
const wargaming = App.use((state) => state.logins.wargaming);
|
2024-09-01 15:46:39 -05:00
|
|
|
|
2024-09-01 17:41:50 -05:00
|
|
|
useEffect(() => {
|
2024-10-09 21:04:49 -05:00
|
|
|
if (!wargaming) return;
|
2024-10-05 16:44:07 -05:00
|
|
|
|
2024-09-01 17:41:50 -05:00
|
|
|
if (id in cache) {
|
|
|
|
|
Promise.all([cache[id]]).then(([votes]) => setVotes(votes));
|
|
|
|
|
} else {
|
|
|
|
|
const cacheable = fetch(
|
|
|
|
|
`/api/tank-voting/${id}/average${
|
|
|
|
|
wargaming ? `?player=${wargaming.id}&token=${wargaming.token}` : ''
|
|
|
|
|
}`,
|
|
|
|
|
)
|
|
|
|
|
.then(
|
|
|
|
|
(response) => response.json() as Promise<BlitzkitResponse<TankVotes>>,
|
|
|
|
|
)
|
|
|
|
|
.then(unwrapBlitzkitResponse);
|
|
|
|
|
cacheable.then(setVotes);
|
|
|
|
|
cache[id] = cacheable;
|
|
|
|
|
}
|
|
|
|
|
}, [id, wargaming]);
|
2024-09-01 15:46:39 -05:00
|
|
|
|
|
|
|
|
return votes;
|
|
|
|
|
}
|