'MapboxGL load callback and useEffect
I'm using Mapbox in a react function component and want to pass down some data to load as a prop.
I'm doing something like this:
const MyMap = (props) => {
const mapContainer = useRef(null);
const map = useRef(null);
useEffect(() => {
map.current = new mapboxgl.Map({
container: mapContainer.current,
style: 'mapbox://styles/mapbox/streets-v11',
zoom: zoom,
});
map.current.on('load', () => {
map.current.addSource('items',
type: 'geojson',
data: { features: props.myData }
});
});
}
The load event fires, but props.myData is empty. props.myData is an empty array when the component initiates (the parent is making an API call to populate it), but is populated by the time load fires. Is the function I'm invoking invoked immediately, and this is why it's not recognizing the new data in the props element? If I, in another useEffect function, set state using the values of that props property, I get the same thing.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
