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

Error handling #96

Merged
merged 2 commits into from
Jan 17, 2024
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
33 changes: 16 additions & 17 deletions app/components/MapView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,15 @@ const Map: React.FC = () => {
const updateBuses = async () => {
if (!selectedRoute || !authToken) return

let busesResponse: IGetVehiclesResponse
let busesResponse: IGetVehiclesResponse = []
try {
busesResponse = await getVehicles([selectedRoute.key], authToken) as IGetVehiclesResponse;

GetVehiclesResponseSchema.parse(busesResponse);
} catch (error) {
console.error(error);
// prevent alert loop from filling screen with alerts.
clearBusRefreshInterval()
throw new Error("Error while updating buses");
clearBusRefreshInterval();
}

if (busesResponse.length == 0 || !busesResponse[0]?.vehiclesByDirections) {
Expand All @@ -66,7 +65,7 @@ const Map: React.FC = () => {

setBuses(extracted)
}

function selectRoute(route: IMapRoute) {
if (selectedRoute?.key === route.key) return;

Expand Down Expand Up @@ -109,18 +108,18 @@ const Map: React.FC = () => {
setZoomToStopLatLng((lat, lng) => {
// Animate map to the current location
const region = {
latitude: lat-.002,
latitude: lat - .002,
longitude: lng,
latitudeDelta: 0.005,
longitudeDelta: 0.005
};

mapViewRef.current?.animateToRegion(region, 250);
})

}, []);



const centerViewOnRoutes = () => {
let coords: LatLng[] = [];
Expand Down Expand Up @@ -174,7 +173,7 @@ const Map: React.FC = () => {

// Animate map to the current location
const region = {
latitude: location.coords.latitude-.002,
latitude: location.coords.latitude - .002,
longitude: location.coords.longitude,
latitudeDelta: 0.01,
longitudeDelta: 0.01
Expand All @@ -184,14 +183,14 @@ const Map: React.FC = () => {

setIsViewCenteredOnUser(true);
}

return (
<>
<MapView
showsUserLocation={true}
style={{ width: "100%", height: "100%" }}
ref={mapViewRef} rotateEnabled={false}
initialRegion={defaultMapRegion}
<MapView
showsUserLocation={true}
style={{ width: "100%", height: "100%" }}
ref={mapViewRef} rotateEnabled={false}
initialRegion={defaultMapRegion}
onPanDrag={() => setIsViewCenteredOnUser(false)}
showsMyLocationButton={false} // we have our own
>
Expand All @@ -211,14 +210,14 @@ const Map: React.FC = () => {
})

return (
<Polyline key={drawnRoute.key} coordinates={coords} strokeColor={lineColor} strokeWidth={4} onPress={() => selectRoute(drawnRoute)}/>
<Polyline key={drawnRoute.key} coordinates={coords} strokeColor={lineColor} strokeWidth={4} onPress={() => selectRoute(drawnRoute)} />
)
})}

{selectedRoute && selectedRoute?.patternPaths.flatMap((patternPath, index1) => (
patternPath.patternPoints.map((patternPoint, index2) => {
const stop = patternPoint.stop

if (stop) {
const lineColor = selectedRoute?.directionList[0]?.lineColor ?? "#FFFF";

Expand Down
42 changes: 26 additions & 16 deletions app/components/sheets/RouteDetails.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect, useState } from "react";
import { View, Text, TouchableOpacity, NativeSyntheticEvent, Alert } from "react-native";
import { View, Text, TouchableOpacity, NativeSyntheticEvent } from "react-native";
import { BottomSheetModal, BottomSheetView, BottomSheetFlatList } from "@gorhom/bottom-sheet";
import SegmentedControl, { NativeSegmentedControlIOSChangeEvent } from "@react-native-segmented-control/segmented-control";
import { Ionicons } from '@expo/vector-icons';
Expand All @@ -25,13 +25,15 @@ const RouteDetails: React.FC<SheetProps> = ({ sheetRef }) => {

const stopEstimates = useAppStore((state) => state.stopEstimates);
const setStopEstimates = useAppStore(state => state.setStopEstimates);

// Controls SegmentedControl
const [selectedDirectionIndex, setSelectedDirectionIndex] = useState(0);

const [processedStops, setProcessedStops] = useState<IStop[]>([]);
const [selectedRoute, setSelectedRoute] = useState<IMapRoute | null>(null);

const [error, setError] = useState(false);

// cleanup this view when the sheet is closed
const closeModal = () => {
sheetRef.current?.dismiss();
Expand Down Expand Up @@ -88,19 +90,24 @@ const RouteDetails: React.FC<SheetProps> = ({ sheetRef }) => {
const newStopEstimates: ICachedStopEstimate[] = [];

// load stop estimates concurrently
const promises = allStops.map(stop =>
getNextDepartureTimes(currentSelectedRoute.key, directionKeys, stop.stopCode, authToken)
.then(response => {
GetNextDepartTimesResponseSchema.parse(response);

newStopEstimates.push({ stopCode: stop.stopCode, departureTimes: response });
})
.catch(error => {
console.error(error);

Alert.alert("Something went wrong", "Some features may not work correctly. Please try again later.");
})
);
const promises = allStops.map(async stop => {
try {
const response = await getNextDepartureTimes(currentSelectedRoute.key, directionKeys, stop.stopCode, authToken);
GetNextDepartTimesResponseSchema.parse(response);

newStopEstimates.push({ stopCode: stop.stopCode, departureTimes: response });
} catch (error) {
console.error(error);

setError(true);

// Make sure to return as if we don't the error state will be reset by the next line
return;
}

// If we rerun the request and there is no error, make sure to reset the error state
setError(false);
});

await Promise.all(promises);
setStopEstimates(newStopEstimates);
Expand All @@ -112,6 +119,7 @@ const RouteDetails: React.FC<SheetProps> = ({ sheetRef }) => {

const snapPoints = ['25%', '45%', '85%'];


return (
<BottomSheetModal
ref={sheetRef}
Expand Down Expand Up @@ -145,8 +153,10 @@ const RouteDetails: React.FC<SheetProps> = ({ sheetRef }) => {
<View style={{ height: 1, backgroundColor: "#eaeaea", marginTop: 8 }} />
</BottomSheetView>
}

{ error && <Text style={{ textAlign: 'center', marginTop: 10 }}>Something went wrong. Please try again later</Text> }

{selectedRoute &&
{!error && selectedRoute &&
<BottomSheetFlatList
data={processedStops}
extraData={[...stopEstimates]}
Expand Down
108 changes: 56 additions & 52 deletions app/components/sheets/StopTimetable.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
import { ActivityIndicator, Alert, Text, TouchableOpacity, View } from "react-native";
import { ActivityIndicator, Text, TouchableOpacity, View } from "react-native";
import { BottomSheetModal, BottomSheetView, BottomSheetScrollView } from "@gorhom/bottom-sheet";
import { FlatList } from "react-native-gesture-handler";
import { getStopSchedules } from "aggie-spirit-api";
Expand Down Expand Up @@ -29,6 +29,8 @@ const StopTimetable: React.FC<SheetProps> = ({ sheetRef }) => {
const [nonRouteSchedules, setNonRouteSchedules] = useState<IRouteStopSchedule[] | null>(null);
const [routeSchedules, setRouteSchedules] = useState<IRouteStopSchedule[] | null>(null);

const [error, setError] = useState(false);

async function loadSchedule(newSelectedStop: IStop | null = null) {
if (!newSelectedStop || !authToken) return;

Expand All @@ -54,7 +56,10 @@ const StopTimetable: React.FC<SheetProps> = ({ sheetRef }) => {
} catch (error) {
console.error(error);

Alert.alert("Something went wrong", "Some features may not work correctly. Please try again later.");
setError(true);

// Make sure to return as if we don't the error state will be reset by the next line
return;
}
}

Expand Down Expand Up @@ -98,64 +103,63 @@ const StopTimetable: React.FC<SheetProps> = ({ sheetRef }) => {
</View>
<View style={{ height: 1, backgroundColor: "#eaeaea", marginTop: 8 }} />

{!routeSchedules && <ActivityIndicator style={{ marginTop: 16 }} />}
{!routeSchedules && !error && <ActivityIndicator style={{ marginTop: 16 }} />}
</BottomSheetView>

{routeSchedules && (<BottomSheetScrollView style={{ flex: 1 }} contentContainerStyle={{ paddingBottom: 35, paddingTop: 4 }}>
{routeSchedules &&
<FlatList
data={routeSchedules}
scrollEnabled={false}
keyExtractor={(_, index) => index.toString()}
ItemSeparatorComponent={() => <View style={{ height: 1, backgroundColor: "#eaeaea", marginVertical: 8 }} />}
renderItem={({ item, index }) => {
return (
<View key={index}>
<Timetable item={item} tintColor={getLineColor(item.routeNumber)} stopCode={selectedStop?.stopCode ?? ""} />
</View>
)
}}
/>
}

{showNonRouteSchedules &&
<View>
<View style={{ height: 1, backgroundColor: "#eaeaea", marginVertical: 8 }} />
{ error && <Text style={{ textAlign: 'center', marginTop: 10 }}>Something went wrong. Please try again later</Text> }

{!error && routeSchedules && (
<BottomSheetScrollView style={{ flex: 1 }} contentContainerStyle={{ paddingBottom: 35, paddingTop: 4 }}>
{routeSchedules && (
<FlatList
data={nonRouteSchedules}
keyExtractor={(_, index) => index.toString()}
data={routeSchedules}
scrollEnabled={false}
keyExtractor={(_, index) => index.toString()}
ItemSeparatorComponent={() => <View style={{ height: 1, backgroundColor: "#eaeaea", marginVertical: 8 }} />}
renderItem={({ item }) => {


renderItem={({ item, index }) => {
return (
<Timetable item={item} tintColor={getLineColor(item.routeNumber)} stopCode={selectedStop?.stopCode ?? ""} />
)
<View key={index}>
<Timetable item={item} tintColor={getLineColor(item.routeNumber)} stopCode={selectedStop?.stopCode ?? ""} />
</View>
);
}}
/>
</View>
}

{nonRouteSchedules && nonRouteSchedules.length > 0 &&
// show other routes button
<TouchableOpacity
style={{
padding: 8,
paddingHorizontal: 16,
marginHorizontal: 16,
borderRadius: 8,
marginTop: 16,
alignSelf: 'center',
backgroundColor: getLineColor(selectedRoute?.shortName ?? "#550000"),
}}
onPress={() => setShowNonRouteSchedules(!showNonRouteSchedules)}
>
<Text style={{ color: "white" }}>{showNonRouteSchedules ? "Hide" : "Show"} Other Routes</Text>
</TouchableOpacity>
}

</BottomSheetScrollView>)}
)}

{showNonRouteSchedules && (
<View>
<View style={{ height: 1, backgroundColor: "#eaeaea", marginVertical: 8 }} />
<FlatList
data={nonRouteSchedules}
keyExtractor={(_, index) => index.toString()}
scrollEnabled={false}
ItemSeparatorComponent={() => <View style={{ height: 1, backgroundColor: "#eaeaea", marginVertical: 8 }} />}
renderItem={({ item }) => {
return <Timetable item={item} tintColor={getLineColor(item.routeNumber)} stopCode={selectedStop?.stopCode ?? ""} />;
}}
/>
</View>
)}

{nonRouteSchedules && nonRouteSchedules.length > 0 && (
// show other routes button
<TouchableOpacity
style={{
padding: 8,
paddingHorizontal: 16,
marginHorizontal: 16,
borderRadius: 8,
marginTop: 16,
alignSelf: 'center',
backgroundColor: getLineColor(selectedRoute?.shortName ?? "#550000"),
}}
onPress={() => setShowNonRouteSchedules(!showNonRouteSchedules)}
>
<Text style={{ color: "white" }}>{showNonRouteSchedules ? "Hide" : "Show"} Other Routes</Text>
</TouchableOpacity>
)}
</BottomSheetScrollView>
)}
</BottomSheetModal>
)
}
Expand Down
14 changes: 8 additions & 6 deletions app/components/ui/FavoritePill.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@


import React, { memo, useEffect, useState } from 'react'
import { Alert, TouchableOpacity } from 'react-native';
import { TouchableOpacity, Alert } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {FontAwesome} from '@expo/vector-icons';

Expand All @@ -26,7 +24,9 @@ const FavoritePill: React.FC<Props> = ({ routeId }) => {
} catch(error) {
console.error(error);

Alert.alert("Something went wrong", "Some features may not work correctly. Please try again later.");
Alert.alert("Something Went Wrong", "Please try again later")

return;
}
}, [])

Expand Down Expand Up @@ -62,10 +62,12 @@ const FavoritePill: React.FC<Props> = ({ routeId }) => {
} catch (error) {
console.error(error);

Alert.alert("Something went wrong", "Some features may not work correctly. Please try again later.");
Alert.alert("Something Went Wrong", "Please try again later");

return;
}
}

return (
<TouchableOpacity onPress={toggleFavorite}>
{isFavorite ?
Expand Down
Loading