Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: cancel request when input get clear #325

Merged
merged 10 commits into from
Dec 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/api/gapsService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import moment, { Moment } from 'moment-timezone'
import { GapsList } from '../model/gaps'
import axios from 'axios'
import axios, { CancelTokenSource } from 'axios'
import { BASE_PATH } from './apiConfig'

type RawGapsList = {
Expand Down Expand Up @@ -28,6 +28,7 @@ export const getGapsAsync = async (
toTimestamp: Moment,
operatorId: string,
lineRef: number,
token: CancelTokenSource['token'],
): Promise<GapsList> => {
const fromDay = moment(fromTimestamp).startOf('day')
const toDay = moment(toTimestamp).startOf('day')
Expand All @@ -42,6 +43,7 @@ export const getGapsAsync = async (
operator_ref: operatorId,
line_ref: lineRef,
},
cancelToken: token,
})
).data
: EXAMPLE_DATA
Expand Down
18 changes: 11 additions & 7 deletions src/api/gtfsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@ export async function getRoutesAsync(
toTimestamp: moment.Moment,
operatorId: string | undefined,
lineNumber: string | undefined,
signal?: AbortSignal | undefined,
): Promise<BusRoute[]> {
const gtfsRoutes = await GTFS_API.gtfsRoutesListGet({
routeShortName: lineNumber,
operatorRefs: operatorId,
dateFrom: fromTimestamp.startOf('day').toDate(),
dateTo: moment.min(toTimestamp.endOf('day'), moment()).toDate(),
limit: 100,
})
const gtfsRoutes = await GTFS_API.gtfsRoutesListGet(
{
routeShortName: lineNumber,
operatorRefs: operatorId,
dateFrom: fromTimestamp.startOf('day').toDate(),
dateTo: moment.min(toTimestamp.endOf('day'), moment()).toDate(),
limit: 100,
},
{ signal },
)
const routes = Object.values(
gtfsRoutes
.filter((route) => route.date.getDate() === toTimestamp.date())
Expand Down
6 changes: 5 additions & 1 deletion src/pages/TimelinePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,22 @@ const TimelinePage = () => {
}, [clearRoutes, operatorId, lineNumber])

useEffect(() => {
const controller = new AbortController()
const signal = controller.signal
clearStops()
if (!operatorId || operatorId === '0' || !lineNumber) {
return
}
setRoutesIsLoading(true)
getRoutesAsync(moment(timestamp), moment(timestamp), operatorId, lineNumber)
getRoutesAsync(moment(timestamp), moment(timestamp), operatorId, lineNumber, signal)
.then((routes) =>
setSearch((current) =>
search.lineNumber === lineNumber ? { ...current, routes: routes } : current,
),
)
.catch((err) => console.error(err.message))
.finally(() => setRoutesIsLoading(false))
return () => controller.abort()
}, [operatorId, lineNumber, clearRoutes, clearStops, timestamp, setState])

const selectedRoute = useMemo(
Expand Down
19 changes: 16 additions & 3 deletions src/pages/gaps/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { FormControlLabel, Switch } from '@mui/material'
import Grid from '@mui/material/Unstable_Grid2' // Grid version 2
import { INPUT_SIZE } from 'src/resources/sizes'
import DisplayGapsPercentage from '../components/DisplayGapsPercentage'
import axios from 'axios'

const Cell = styled.div`
width: 120px;
Expand All @@ -34,7 +35,6 @@ const GapsPage = () => {
const { search, setSearch } = useContext(SearchContext)
const { operatorId, lineNumber, timestamp, routes, routeKey } = search
const [gaps, setGaps] = useState<GapsList>()

const [routesIsLoading, setRoutesIsLoading] = useState(false)
const [gapsIsLoading, setGapsIsLoading] = useState(false)
const [onlyGapped, setOnlyGapped] = useSessionStorage('onlyGapped', false)
Expand Down Expand Up @@ -66,19 +66,29 @@ const GapsPage = () => {
}

useEffect(() => {
const source = axios.CancelToken.source()
if (operatorId && routes && routeKey && timestamp) {
const selectedRoute = routes.find((route) => route.key === routeKey)
if (!selectedRoute) {
return
}
setGapsIsLoading(true)
getGapsAsync(moment(timestamp), moment(timestamp), operatorId, selectedRoute.lineRef)
getGapsAsync(
moment(timestamp),
moment(timestamp),
operatorId,
selectedRoute.lineRef,
source.token,
)
.then(setGaps)
.finally(() => setGapsIsLoading(false))
}
return () => source.cancel()
}, [operatorId, routeKey, timestamp])

useEffect(() => {
const controller = new AbortController()
const signal = controller.signal
if (!operatorId || operatorId === '0' || !lineNumber) {
setSearch((current) => ({
...current,
Expand All @@ -87,13 +97,16 @@ const GapsPage = () => {
}))
return
}
getRoutesAsync(moment(timestamp), moment(timestamp), operatorId, lineNumber)
setRoutesIsLoading(true)
getRoutesAsync(moment(timestamp), moment(timestamp), operatorId, lineNumber, signal)
.then((routes) =>
setSearch((current) =>
search.lineNumber === lineNumber ? { ...current, routes: routes } : current,
),
)
.catch((err) => console.error(err.message))
.finally(() => setRoutesIsLoading(false))
return () => controller.abort()
}, [operatorId, lineNumber, timestamp, setSearch])

const gapsPercentage = getGapsPercentage(gaps)
Expand Down
8 changes: 6 additions & 2 deletions src/pages/gapsPatterns/GapsPatternsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -150,24 +150,28 @@ const GapsPatternsPage = () => {
const [routesIsLoading, setRoutesIsLoading] = useState(false)
const { t } = useTranslation()

const loadSearchData = async () => {
const loadSearchData = async (signal: AbortSignal | undefined) => {
setRoutesIsLoading(true)
const routes = await getRoutesAsync(
moment(startDate),
moment(endDate),
operatorId as string,
lineNumber as string,
signal,
)
setSearch((current) => (search.lineNumber === lineNumber ? { ...current, routes } : current))
setRoutesIsLoading(false)
}

useEffect(() => {
const controller = new AbortController()
const signal = controller.signal
if (!operatorId || operatorId === '0' || !lineNumber) {
setSearch((current) => ({ ...current, routeKey: undefined, routes: undefined }))
return
}
loadSearchData()
loadSearchData(signal)
return () => controller.abort()
}, [operatorId, lineNumber, endDate, startDate, setSearch])

return (
Expand Down
11 changes: 10 additions & 1 deletion src/pages/gapsPatterns/useGapsList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { getGapsAsync } from '../../api/gapsService'

import { sortByMode, HourlyData } from '../components/utils'
import { GapsList } from 'src/model/gaps'
import axios from 'axios'

type HourlyDataList = HourlyData[]
// Convert gapsList into HourlyDataList structure
Expand Down Expand Up @@ -44,11 +45,19 @@ export const useGapsList = (
const [hourlyData, setHourlyData] = useState<HourlyData[]>([])

useEffect(() => {
const source = axios.CancelToken.source()
const fetchData = async () => {
try {
const gapsList: GapsList = await getGapsAsync(fromDate, toDate, operatorRef, lineRef)
const gapsList: GapsList = await getGapsAsync(
fromDate,
toDate,
operatorRef,
lineRef,
source.token,
)
const result = convertGapsToHourlyStruct(gapsList)
setHourlyData(sortByMode(result, sortingMode))
return () => source.cancel()
} catch (error) {
console.error('Error fetching data:', error)
}
Expand Down
12 changes: 8 additions & 4 deletions src/pages/singleLineMap/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,19 @@ const SingleLineMapPage = () => {
}, [])

useEffect(() => {
const controller = new AbortController()
const signal = controller.signal
if (!operatorId || operatorId === '0' || !lineNumber) {
setSearch((current) => ({ ...current, routes: undefined, routeKey: undefined }))
return
}
getRoutesAsync(moment(timestamp), moment(timestamp), operatorId, lineNumber).then((routes) =>
setSearch((current) =>
search.lineNumber === lineNumber ? { ...current, routes: routes } : current,
),
getRoutesAsync(moment(timestamp), moment(timestamp), operatorId, lineNumber, signal).then(
(routes) =>
setSearch((current) =>
search.lineNumber === lineNumber ? { ...current, routes: routes } : current,
),
)
return () => controller.abort()
}, [operatorId, lineNumber, timestamp])

const selectedRoute = useMemo(
Expand Down
Loading