Rework the watch status observer to update every 10s

This commit is contained in:
Zoe Roux 2023-12-05 01:46:11 +01:00
parent 1eb7198e6f
commit 74013cf113

View File

@ -20,8 +20,9 @@
import { WatchStatusV, queryFn } from "@kyoo/models"; import { WatchStatusV, queryFn } from "@kyoo/models";
import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react"; import { useEffect, useCallback } from "react";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useAtomCallback } from "jotai/utils";
import { playAtom, progressAtom } from "./state"; import { playAtom, progressAtom } from "./state";
export const WatchStatusObserver = ({ export const WatchStatusObserver = ({
@ -32,7 +33,7 @@ export const WatchStatusObserver = ({
slug: string; slug: string;
}) => { }) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const mutation = useMutation({ const { mutate } = useMutation({
mutationFn: (seconds: number) => mutationFn: (seconds: number) =>
queryFn({ queryFn({
path: [ path: [
@ -46,13 +47,28 @@ export const WatchStatusObserver = ({
onSettled: async () => onSettled: async () =>
await queryClient.invalidateQueries({ queryKey: [type === "episode" ? "show" : type, slug] }), await queryClient.invalidateQueries({ queryKey: [type === "episode" ? "show" : type, slug] }),
}); });
const readProgress = useAtomCallback(
useCallback((get) => {
const currCount = get(progressAtom);
return currCount;
}, []),
);
const isPlaying = useAtomValue(playAtom); // update watch status every 10 seconds and on unmount.
const progress = useAtomValue(progressAtom);
useEffect(() => { useEffect(() => {
mutation.mutate(progress); const timer = setInterval(() => {
// Do not make a request every seconds. mutate(readProgress());
// eslint-disable-next-line react-hooks/exhaustive-deps }, 10_000);
}, [type, slug, isPlaying]); return () => {
clearInterval(timer);
mutate(readProgress());
};
}, [type, slug, readProgress, mutate]);
// update watch status when play status change (and on mount).
const isPlaying = useAtomValue(playAtom);
useEffect(() => {
mutate(readProgress())
}, [type, slug, isPlaying, readProgress, mutate])
return null; return null;
}; };