refactor: NPED Context, sound update and start session

This commit is contained in:
2025-09-25 10:38:49 +01:00
parent efd037754e
commit 80b407943f
20 changed files with 96 additions and 39 deletions

View File

@@ -2,25 +2,30 @@ import { useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import type { SightingType } from "../types/types";
import { useSoundOnChange } from "react-sounds";
import click from "../assets/sounds/ui/computer-mouse-click.mp3";
import switchSound from "../assets/sounds/ui/switch.mp3";
async function fetchSighting(url: string, ref: number): Promise<SightingType> {
async function fetchSighting(
url: string | undefined,
ref: number
): Promise<SightingType> {
const res = await fetch(`${url}${ref}`);
if (!res.ok) throw new Error(String(res.status));
return res.json();
}
export function useSightingFeed(url: string, side: string) {
export function useSightingFeed(url: string | undefined) {
const [sightings, setSightings] = useState<SightingType[]>([]);
const [selectedRef, setSelectedRef] = useState<number | null>(null);
const [sessionStarted, setSessionStarted] = useState(false);
const [sessionList, setSessionList] = useState<SightingType[]>([]);
const mostRecent = sightings[0] ?? null;
const latestRef = mostRecent?.ref ?? null;
const [selectedSighting, setSelectedSighting] = useState<SightingType | null>(
null
);
useSoundOnChange(click, latestRef, {
volume: side === "Rear" ? 0 : 1,
useSoundOnChange(switchSound, latestRef, {
volume: 1,
});
const currentRef = useRef<number>(-1);
@@ -52,6 +57,13 @@ export function useSightingFeed(url: string, side: string) {
staleTime: 0,
});
useEffect(() => {
if (sessionStarted) {
if (!mostRecent) return;
setSessionList([...sessionList, mostRecent]);
}
}, [mostRecent, sessionList, sessionStarted]);
useEffect(() => {
const data = query.data;
if (!data) return;
@@ -92,13 +104,15 @@ export function useSightingFeed(url: string, side: string) {
// console.error("Sighting feed error:", query.error);
}
}, [query.error]);
return {
sightings,
selectedRef,
setSelectedRef,
mostRecent,
selectedSighting,
sessionList,
sessionStarted,
setSessionStarted,
setSelectedSighting,
data: query.data,
isLoading: query.isLoading,