fix: prevent duplicate API instances in MapContainer

- fixed state management bug where API instances were appended to existing array instead of replacing it
- this caused duplicate API instances in React Strict Mode and potential memory leaks
- replaced setApis((current) => [...current, newApi]) with proper array replacement

- compute full API array from layers, then replace state completely
- use .map() for transformation instead of side effects
- the apis array has 1:1 relationship with layers (matched by ID), so accumulation was never intended
This commit is contained in:
mahula 2025-11-20 20:10:31 +01:00
parent 61f2ee0993
commit 477a9d5c02

View File

@ -36,12 +36,12 @@ function MapContainer({ layers, map }: { layers: LayerProps[]; map: any }) {
const [apis, setApis] = useState<layerApi[]>([]) const [apis, setApis] = useState<layerApi[]>([])
useEffect(() => { useEffect(() => {
// get timestamp for the end of the current day // get timestamp for the start of the current day
const now = new Date() const now = new Date()
const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate()) const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate())
const startOfDayISO = startOfDay.toISOString() const startOfDayISO = startOfDay.toISOString()
layers.map((layer: LayerProps) => { const newApis = layers.map((layer: LayerProps) => {
// Only apply date filter if showPastItems is not explicitly set to true // Only apply date filter if showPastItems is not explicitly set to true
const dateFilter = layer.showPastItems const dateFilter = layer.showPastItems
? undefined ? undefined
@ -60,15 +60,13 @@ function MapContainer({ layers, map }: { layers: LayerProps[]; map: any }) {
], ],
} }
apis && return {
setApis((current) => [ id: layer.id,
...current, api: new itemsApi<Place>('items', layer.id, undefined, dateFilter),
{ }
id: layer.id,
api: new itemsApi<Place>('items', layer.id, undefined, dateFilter),
},
])
}) })
setApis(newApis)
}, [layers]) }, [layers])
useEffect(() => {}, [apis]) useEffect(() => {}, [apis])