From 9910efe5071784dc009176f2ab254324532300cd Mon Sep 17 00:00:00 2001 From: Emmy D'Anello Date: Fri, 2 Feb 2024 22:54:19 +0100 Subject: [PATCH] Improve client cache and bug fix --- sncf-station/src/TrainsTable.js | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/sncf-station/src/TrainsTable.js b/sncf-station/src/TrainsTable.js index 7f1fa06..3238f9c 100644 --- a/sncf-station/src/TrainsTable.js +++ b/sncf-station/src/TrainsTable.js @@ -10,8 +10,8 @@ import { Typography } from "@mui/material" import {CSSTransition, TransitionGroup} from 'react-transition-group' -import {useQueries, useQuery, useQueryClient} from "@tanstack/react-query"; -import {useEffect, useState} from "react"; +import {useQueries, useQuery} from "@tanstack/react-query"; +import {useCallback, useEffect, useMemo} from "react"; const StyledTableRow = styled(TableRow)(({ theme, tableType }) => ({ 'tbody &:nth-of-type(odd)': { @@ -50,37 +50,32 @@ function TrainsTableHeader({tableType}) { } function TrainsTableBody({stop, date, time, tableType}) { - const queryClient = useQueryClient() - - let filterTime = (train) => { - if (train.departure_time === "04:56:00") - return false + const filterTime = useCallback((train) => { if (tableType === "departures") return `${train.departure_date}T${train.departure_time_24h}` >= `${date}T${time}` else return `${train.arrival_date}T${train.arrival_time_24h}` >= `${date}T${time}` - } + }, [date, time, tableType]) - function updateTrains() { + const updateTrains = useCallback(() => { return fetch(`/api/station/next_${tableType}/?stop_id=${stop.id}&date=${date}&time=${time}&offset=${0}&limit=${20}`) .then(response => response.json()) .then(data => data.results) .then(data => [...data]) - } + }, [stop.id, date, time, tableType]) const trainsQuery = useQuery({ queryKey: ['trains', stop.id, tableType], queryFn: updateTrains, enabled: !!stop.id, }) - const trains = trainsQuery.data ?? [] + const trains = useMemo(() => trainsQuery.data ?? [], [trainsQuery.data]) useEffect(() => { let validTrains = trains?.filter(filterTime) ?? [] - console.log(validTrains.length) - if (trains?.length > 0 && validTrains.length <= trains?.length) - queryClient.invalidateQueries({queryKey: ['trains', stop.id, tableType]}) - }, [stop.id, tableType, date, time]) + if (trains?.length > 0 && validTrains.length < trains?.length) + trainsQuery.refetch().then() + }, [trains, filterTime, trainsQuery]) let table_rows = trains.map((train) =>