Skip to content

Commit

Permalink
front: Implement caching mechanism for region geometries in RegionMap…
Browse files Browse the repository at this point in the history
… component.

This commit introduces a caching strategy in the MapComponent of the RegionMap
module. The primary change involves the addition of a useRef hook to maintain a
cache of the last 10 fetched region geometries. This cache is an array stored
in regionGeometryCache.

The fetchSelectedRegionGeometry function is updated to first check if the
selected region's geometry is already available in the cache. If not found, it
fetches the geometry from the API, adds it to the cache, and ensures that the
cache size does not exceed 10 items by removing the oldest entry when
necessary.

Issue: #103

Signed-off-by: Nikolay Martyanov <[email protected]>
  • Loading branch information
OhmSpectator committed Dec 5, 2023
1 parent d10ea6f commit 03325da
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion frontend/src/components/RegionMap.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,36 @@ function MapComponent() {
const mapContainer = useRef(null);
const map = useRef(null);
const { selectedRegion, selectedHierarchy } = useNavigation();
const regionGeometryCache = useRef([]);

const fetchSelectedRegionGeometry = async () => {
const cacheIndex = regionGeometryCache.current.findIndex(
(item) => item.id === selectedRegion.id && item.hierarchyId === selectedHierarchy.hierarchyId,
);

// Check if the geometry for the selected region is already in the cache
if (cacheIndex !== -1) {
return regionGeometryCache.current[cacheIndex].geometry;
}

if (selectedRegion.id !== null && selectedRegion.id !== 0) {
const response = await fetchRegionGeometry(selectedRegion.id, selectedHierarchy.hierarchyId);
if (response) {
// Add new geometry to the cache, managing the cache size
if (regionGeometryCache.current.length >= 10) {
regionGeometryCache.current.shift(); // Remove the oldest item
}
regionGeometryCache.current.push({
id: selectedRegion.id,
hierarchyId: selectedHierarchy.hierarchyId,
geometry: response.geometry,
});
return response.geometry;
}
return null;
}
return null;
};

const initializeMap = async () => {
if (!mapContainer.current) return; // wait for map container to load

Expand Down

0 comments on commit 03325da

Please sign in to comment.