Skip to content

Commit c1a234c

Browse files
sjain2025cirex-web
authored andcommitted
use memoization
1 parent 6a93325 commit c1a234c

1 file changed

Lines changed: 34 additions & 13 deletions

File tree

src/App.tsx

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from 'react';
1+
import React, { useMemo } from 'react';
22
import { BrowserRouter, Route, Routes } from 'react-router-dom';
33
import { Toaster } from 'react-hot-toast';
44
import Navbar from './components/Navbar';
@@ -23,22 +23,43 @@ export default function App() {
2323
const { userCoordinates } = useUserLocation();
2424
// Load locations
2525
const { data, error } = $api.useQuery('get', '/v2/locations');
26-
const locations = data?.map((location) => ({
27-
...location,
28-
name: toTitleCase(location.name ?? 'Untitled'), // Convert names to title case
29-
})) satisfies ILocation_FromAPI[] | undefined;
26+
const locations = useMemo(
27+
() =>
28+
data?.map((location) => ({
29+
...location,
30+
name: toTitleCase(location.name ?? 'Untitled'), // Convert names to title case
31+
})) satisfies ILocation_FromAPI[] | undefined,
32+
[data],
33+
);
3034

3135
const [cardViewPreferences, setCardViewPreferences] = useUserCardViewPreferences();
3236
useRefreshWhenBackOnline();
3337

34-
const fullLocationData: ILocation_Full[] | undefined = locations?.map((location) => ({
35-
...location,
36-
...getLocationStatus(location.times, now),
37-
cardViewPreference:
38-
cardViewPreferences[location.id] ?? cardViewPreferences[location.conceptId ?? ''] ?? 'normal', // check for conceptid preference as well, fallback
39-
distanceFromUserMeters:
40-
userCoordinates === null ? null : (getLocationDistanceFromUser(location, userCoordinates) ?? null),
41-
}));
38+
const distanceFromUserMetersByLocationId = useMemo(() => {
39+
if (!locations) return undefined;
40+
const out: Record<string, number | null> = {};
41+
if (userCoordinates === null) {
42+
for (const location of locations) {
43+
out[location.id] = null;
44+
}
45+
return out;
46+
}
47+
for (const location of locations) {
48+
out[location.id] = getLocationDistanceFromUser(location, userCoordinates) ?? null;
49+
}
50+
return out;
51+
}, [locations, userCoordinates]);
52+
53+
const fullLocationData: ILocation_Full[] | undefined = useMemo(() => {
54+
if (!locations || !distanceFromUserMetersByLocationId) return undefined;
55+
return locations.map((location) => ({
56+
...location,
57+
...getLocationStatus(location.times, now),
58+
cardViewPreference:
59+
cardViewPreferences[location.id] ?? cardViewPreferences[location.conceptId ?? ''] ?? 'normal', // check for conceptid preference as well, fallback
60+
distanceFromUserMeters: distanceFromUserMetersByLocationId[location.id] ?? null,
61+
}));
62+
}, [locations, now, cardViewPreferences, distanceFromUserMetersByLocationId]);
4263

4364
return (
4465
<React.StrictMode>

0 commit comments

Comments
 (0)