mapbox / mapbox/mapbox-gl-geocoder

Geocoder input reinitializes repeatedly in dev mode (react + useEffect)

Open
#406 4 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

auto-triaged enhancement
Dominant language
JavaScript
Stars
388
Forks
181
PR merge metrics
No merged PRs in 30d

Description

System Info
---
OS macOS 10.13.6 High Sierra
Node version 14.15
Libraries:
- mapbox-gl
- MapboxGeocoder
- create-react-app
- tailwindcss@2
- craco

Symptoms
---

I'm using the geocoder js library in a react application and seeing that the input is rendered each time my development server restarts (create react app fast refresh). I believe the appropriate enhancement is to provide a clean up function to remove the geocoder on component unmount, similar to the `map.remove()` function provided by `mapboxgl.Map()` as per the [react example repo](https://github.com/mapbox/mapbox-react-examples/blob/master/basic/src/Map.js#L8)

Code sample
---
```
import { useEffect } from 'react'
import mapboxgl from 'mapbox-gl'
import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder'
import '@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css'

const geocoder = new MapboxGeocoder({
accessToken: process.env.REACT_APP_MB_TOKEN,
mapboxgl: mapboxgl
})

export default function Autocomplete() {
useEffect(() => {
geocoder.addTo('#location')
geocoder.on('result', function ({ result }) {
console.dir(result)
})
}, [])
return


}
```

Screenshot
---

![Autocomplete](https://user-images.githubusercontent.com/75855689/102024325-3b7d3b00-3d46-11eb-9785-b79d52286708.png)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the geocoder.addTo call in the provided React useEffect and compare its lifecycle with the linked React example's map.remove pattern. Inspect the geocoder control's existing cleanup behavior and determine how unmounting should affect the rendered input and registered result handler. Done means development-server refreshes no longer leave duplicate geocoder inputs.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
frontend
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.