Skip to content

fix: handle _leaflet_pos TypeError on chapters map#4296

Open
taditharun wants to merge 7 commits intoOWASP:mainfrom
taditharun:fix/leaflet-typeerror-chapters-map
Open

fix: handle _leaflet_pos TypeError on chapters map#4296
taditharun wants to merge 7 commits intoOWASP:mainfrom
taditharun:fix/leaflet-typeerror-chapters-map

Conversation

@taditharun
Copy link

Proposed change

Resolves #4286

While browsing the chapters page I noticed a JavaScript error
in the browser console. The error occurs when the Date Created
filter is applied and a country is selected from the dropdown.

Error:
Uncaught TypeError: Cannot read properties of undefined
(reading '_leaflet_pos')

The issue is in the MapZoomControl component — leaflet tries
to read the map pane position during zoom transition before
the map container is fully initialized.

Wrapped the map control logic in a try/catch block to handle
this gracefully.

Type of change

  • Bug fix

Checklist

  • I was assigned to this issue before starting work
  • I have read the contributing guidelines
  • My changes do not break any existing functionality

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 18, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds defensive guards in ChapterMap: MapZoomControl and its cleanup now early-return when map.getContainer() is missing; MapViewUpdater wraps effect in try/catch and returns early when the map container is absent. Minor spacing/formatting changes only.

Changes

Cohort / File(s) Summary
Chapter map component
frontend/src/components/ChapterMap.tsx
Added early-return guards when map.getContainer() is falsy in MapZoomControl (effect and cleanup) and MapViewUpdater (effect wrapped in try/catch with early return); adjusted spacing and removed an extra blank line.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • arkid15r
  • kasya
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: fixing a TypeError related to '_leaflet_pos' on the chapters map, which directly matches the code changes in ChapterMap.tsx.
Description check ✅ Passed The description is clearly related to the changeset, detailing the specific error encountered, its location in MapZoomControl, and explaining that the fix involves wrapping logic in a try/catch block to handle uninitialized map containers.
Linked Issues check ✅ Passed The PR successfully addresses issue #4286 by adding null checks for map.getContainer() and wrapping operations in try/catch blocks within MapZoomControl and MapViewUpdater, preventing the '_leaflet_pos' TypeError during uninitialized container states.
Out of Scope Changes check ✅ Passed All code changes are directly scoped to resolving the map container initialization issue in ChapterMap.tsx; no unrelated changes or formatting modifications beyond those necessary for the fix are present.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

cubic-dev-ai[bot]
cubic-dev-ai bot previously approved these changes Mar 18, 2026
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 1 file

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Since this is your first cubic review, here's how it works:

  • cubic automatically reviews your code and comments on bugs and improvements
  • Teach cubic by replying to its comments. cubic learns from your replies and gets better over time
  • Add one-off context when rerunning by tagging @cubic-dev-ai with guidance or docs links (including llms.txt)
  • Ask questions if you need clarification on any suggestion

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@frontend/src/components/ChapterMap.tsx`:
- Line 64: The TSX parse error is caused by a stray "M" after the closing brace
of the ChapterMap component; open the ChapterMap component (component/function
named ChapterMap in frontend/src/components/ChapterMap.tsx), remove the trailing
"M" character following the final "}" so the file ends with a valid closing
brace only, then save and run the TypeScript/TSX build to confirm the parse
error is resolved.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 25bf5973-4f7b-4eab-a341-2300f34339f4

📥 Commits

Reviewing files that changed from the base of the PR and between 027f4f4 and db2481d.

📒 Files selected for processing (1)
  • frontend/src/components/ChapterMap.tsx

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 18, 2026
cubic-dev-ai[bot]
cubic-dev-ai bot previously approved these changes Mar 18, 2026
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Copy link
Contributor

@anurag2787 anurag2787 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @taditharun thanks for working on this
I think we should focus on fixing the root cause of the issue rather than handling it with a try catch
Also please run make check-test locally before pushing your code

@taditharun
Copy link
Author

hiii @anurag2787 , Thanks for the review! Will fix the root cause and run make check-test before pushing.

cubic-dev-ai[bot]
cubic-dev-ai bot previously approved these changes Mar 18, 2026
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
frontend/src/components/ChapterMap.tsx (1)

74-79: ⚠️ Potential issue | 🟡 Minor

Missing null check for map.getContainer() before accessing properties.

MapViewUpdater retrieves the container at line 76 but immediately accesses clientWidth and clientHeight without verifying the container exists. If getContainer() returns undefined (same race condition as the original bug), this will throw a TypeError.

🛡️ Proposed fix to guard container access
   useEffect(() => {
     if (!map) return
     const container = map.getContainer()
+    if (!container) return
     const width = container.clientWidth
     const height = container.clientHeight
     const aspectRatio = height > 0 ? width / height : 1
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@frontend/src/components/ChapterMap.tsx` around lines 74 - 79, The useEffect
block that reads map.getContainer() may receive undefined; add a null check for
the container returned by map.getContainer() before accessing
container.clientWidth or container.clientHeight (inside the same useEffect where
map is checked). If container is falsy, either return early or fall back to safe
defaults for width/height/aspectRatio so no TypeError is thrown; update the
variables computed (width, height, aspectRatio) accordingly in the useEffect
containing map.getContainer().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@frontend/src/components/ChapterMap.tsx`:
- Around line 20-22: The cleanup function inside the useEffect that manipulates
the Leaflet map can run after the map container was removed and therefore should
mirror the defensive checks used on mount; update the cleanup block in the same
useEffect (the function returned from useEffect that references map and calls
map.getContainer(), invalidateSize, or manipulates _leaflet_pos) to first verify
map is defined and map.getContainer() is truthy before performing any map
operations, so the cleanup early-returns if the container is gone and avoids the
_leaflet_pos TypeError.

---

Outside diff comments:
In `@frontend/src/components/ChapterMap.tsx`:
- Around line 74-79: The useEffect block that reads map.getContainer() may
receive undefined; add a null check for the container returned by
map.getContainer() before accessing container.clientWidth or
container.clientHeight (inside the same useEffect where map is checked). If
container is falsy, either return early or fall back to safe defaults for
width/height/aspectRatio so no TypeError is thrown; update the variables
computed (width, height, aspectRatio) accordingly in the useEffect containing
map.getContainer().
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 25a4a499-d606-484e-924e-665f61cd7b1e

📥 Commits

Reviewing files that changed from the base of the PR and between 96ab036 and 11dfff5.

📒 Files selected for processing (1)
  • frontend/src/components/ChapterMap.tsx

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 18, 2026
@taditharun
Copy link
Author

Fixed!, Added null checks for map container in the cleanup effect and MapViewUpdater as well. Ran ChapterMap tests locally 40/40 passed.

cubic-dev-ai[bot]
cubic-dev-ai bot previously approved these changes Mar 18, 2026
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Copy link
Contributor

@anurag2787 anurag2787 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @taditharun i can still see the error
Image

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="frontend/src/components/ChapterMap.tsx">

<violation number="1" location="frontend/src/components/ChapterMap.tsx:127">
P2: Empty broad `catch` swallows all map update errors, masking real failures beyond the intended `_leaflet_pos` teardown case.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
frontend/src/components/ChapterMap.tsx (1)

75-133: ⚠️ Potential issue | 🔴 Critical

Critical: Missing closing brace for useEffect callback causes parse error.

The useEffect callback function is never closed before the dependency array. Line 131 has an orphaned dependency array [userLocation, showLocal, validGeoLocData, map]) that is not syntactically connected to the useEffect call. This is a parse-breaking error that will prevent the application from building.

Additional issues:

  • Line 77: Missing space before { in try{
  • Line 128: Typo "complite" → "complete"
  • Inconsistent indentation throughout the block
🐛 Proposed fix for the parse error and formatting
   useEffect(() => {
     if (!map) return
-    try{
+    try {
-    const container = map.getContainer()
-    if (!container) return
+      const container = map.getContainer()
+      if (!container) return
-    const width = container.clientWidth
-    const height = container.clientHeight
-    const aspectRatio = height > 0 ? width / height : 1
+      const width = container.clientWidth
+      const height = container.clientHeight
+      const aspectRatio = height > 0 ? width / height : 1

-    const dynamicMinZoom = aspectRatio > 2 ? 1 : 2
-    map.setMinZoom(dynamicMinZoom)
+      const dynamicMinZoom = aspectRatio > 2 ? 1 : 2
+      map.setMinZoom(dynamicMinZoom)

-    if (userLocation && validGeoLocData.length > 0) {
+      if (userLocation && validGeoLocData.length > 0) {
         // ... existing code with proper indentation ...
-    } else if (showLocal && validGeoLocData.length > 0) {
+      } else if (showLocal && validGeoLocData.length > 0) {
         // ... existing code with proper indentation ...
-    } else {
-      map.setView([20, 0], Math.max(dynamicMinZoom, 2))
-    } 
-  } catch {
-          // the map container was removed before update complite
-
-  }
-   [userLocation, showLocal, validGeoLocData, map])
-
-   return null
+      } else {
+        map.setView([20, 0], Math.max(dynamicMinZoom, 2))
+      }
+    } catch {
+      // the map container was removed before update complete
+    }
+  }, [userLocation, showLocal, validGeoLocData, map])
+
+  return null
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@frontend/src/components/ChapterMap.tsx` around lines 75 - 133, The useEffect
callback is missing its closing brace before the dependency array which causes a
parse error; close the try/catch/useEffect block properly by adding the required
closing brace and parenthesis so the dependency array [userLocation, showLocal,
validGeoLocData, map] is attached to useEffect, fix the "try{" spacing to "try
{", correct the catch comment typo "complite" → "complete" (or add an error
parameter to catch if needed), and normalize indentation inside the useEffect
(refer to the useEffect callback that reads map.getContainer(),
map.setMinZoom(), map.fitBounds(), map.setView() and the catch block).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@frontend/src/components/ChapterMap.tsx`:
- Around line 75-133: The useEffect callback is missing its closing brace before
the dependency array which causes a parse error; close the try/catch/useEffect
block properly by adding the required closing brace and parenthesis so the
dependency array [userLocation, showLocal, validGeoLocData, map] is attached to
useEffect, fix the "try{" spacing to "try {", correct the catch comment typo
"complite" → "complete" (or add an error parameter to catch if needed), and
normalize indentation inside the useEffect (refer to the useEffect callback that
reads map.getContainer(), map.setMinZoom(), map.fitBounds(), map.setView() and
the catch block).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 696b2cc0-3bd2-4587-9f0a-3969a74be32b

📥 Commits

Reviewing files that changed from the base of the PR and between 702a4bb and 7b62866.

📒 Files selected for processing (1)
  • frontend/src/components/ChapterMap.tsx

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 19, 2026
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Requires human review: Auto-approval blocked by 1 unresolved issue from previous reviews.

@taditharun taditharun force-pushed the fix/leaflet-typeerror-chapters-map branch from 87e2c74 to d2f5c8e Compare March 19, 2026 14:36
@taditharun
Copy link
Author

Hi @arkid15r and @anurag2787 Fixed the root cause and removed try,catch completely and kept only proper null checks for map container. All 40 ChapterMap tests passing locally with 0 errors. I don't have Algolia keys locally so unable to test the full search flow could you verify on your end?

@anurag2787
Copy link
Contributor

Hi @arkid15r and @anurag2787 Fixed the root cause and removed try,catch completely and kept only proper null checks for map container. All 40 ChapterMap tests passing locally with 0 errors. I don't have Algolia keys locally so unable to test the full search flow could you verify on your end?

The error is still occurring on my end also for Algolia you can get a free API key from https://www.algolia.com

@sonarqubecloud
Copy link

@taditharun
Copy link
Author

Hi @anurag2787 !, Got Algolia keys set up and tested locally. The TypeError is fixed applying Date Created filter and selecting a country shows no errors in console. Screenshot attached. Could you please re-review?

Screenshot 2026-03-20 213814

@taditharun
Copy link
Author

Hi @anurag2787 , just wanted to add I also tested on the live production site at nest.owasp.org/chapters and the bug is still reproducible there. Selecting Albania triggers the same Uncaught TypeError: Cannot read properties of undefined
(reading '_leaflet_pos'). My fix resolves this locally. This confirms the fix is needed on production too!!

Screenshot 2026-03-20 224054 ded on production too!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Leaflet map throws TypeError on Chapters page

2 participants