Skip to content
Merged
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
43 changes: 30 additions & 13 deletions src/components/RouteMap/MediaMarkers.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useMap } from '@vis.gl/react-google-maps';
import type { Marker } from '@googlemaps/markerclusterer';
import { useMediaPosts, type MediaPost } from '../../hooks/useMediaPosts';
import MediaMarker from './MediaMarker';
import MediaLightbox from '../MediaLightbox';
Expand All @@ -14,21 +15,37 @@ export default function MediaMarkers() {
const map = useMap();
const setMediaMarkerRef = useClusterer(map, mediaClusterRenderer);

// Keeps the tagging ref callback below stable in identity (see caveat
// on useClusterer: a new function per render causes React to detach/
// reattach every AdvancedMarker's ref on every single render, which
// triggers an infinite setState loop in useClusterer). The post is
// read from this ref instead of being captured directly so the
// wrapper function itself never needs to change.
const postsById = useRef<Record<string, MediaPost>>({});
useEffect(() => {
const next: Record<string, MediaPost> = {};
for (const post of geotagged) next[post.id] = post;
postsById.current = next;
}, [geotagged]);

const taggingRefs = useRef<Record<string, (marker: Marker | null) => void>>({});
function getTaggingRef(id: string) {
if (!taggingRefs.current[id]) {
taggingRefs.current[id] = (marker: Marker | null) => {
// Tag the raw marker instance with its post so the cluster
// renderer (which only receives marker instances, not our
// React props) can pick a thumbnail to show on the bubble.
if (marker) Object.assign(marker, { __mediaPost: postsById.current[id] });
setMediaMarkerRef(id)(marker);
};
}
return taggingRefs.current[id];
}

return (
<>
{geotagged.map((post) => (
<MediaMarker
key={post.id}
post={post}
onClick={() => setSelected(post)}
markerRef={(marker) => {
// Tag the raw marker instance with its post so the cluster
// renderer (which only receives marker instances, not our
// React props) can pick a thumbnail to show on the bubble.
if (marker) Object.assign(marker, { __mediaPost: post });
setMediaMarkerRef(post.id)(marker);
}}
/>
<MediaMarker key={post.id} post={post} onClick={() => setSelected(post)} markerRef={getTaggingRef(post.id)} />
))}
{selected && <MediaLightbox post={selected} onClose={() => setSelected(null)} />}
</>
Expand Down