5

I'm working on a React application that utilizes Mapbox GL for displaying maps. I have a requirement to load GeoJSON data from a URL and update the map accordingly. However, I'm facing an issue where only the initial map is loading, and the map doesn't update with the fetched GeoJSON data.

I've tried fetching the GeoJSON data using fetch and updating the state with the received data, but it doesn't seem to reflect on the map. I've verified that the fetched data is valid GeoJSON and contains the necessary features.

Here's a simplified version of my code:

import React, { useState, useEffect } from "react";
import Map from "react-map-gl";

const MapComponent = () => {
  const [viewState, setViewState] = useState({
    latitude: 45.4250485180001,
    longitude: -71.955837277,
    zoom: 14,
  });
  const [geojsonData, setGeojsonData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(
          "https://example.com/api/geojson-data"
        );
        const data = await response.json();
        setGeojsonData(data);
      } catch (error) {
        console.error("Failed to fetch GeoJSON data:", error);
      }
    };

    fetchData();
  }, []);

  return (
    <Map
      {...viewState}
      // Mapbox GL props
    >
      {/* Map layers and features */}
    </Map>
  );
};

export default MapComponent;

I've verified that the geojsonData state is updated with the fetched GeoJSON data by logging it to the console. However, the map doesn't show the features from the GeoJSON data. It only displays the initial map centered at the default coordinates.

What could be causing this issue? Am I missing something in my implementation? Any help or guidance would be greatly appreciated.

Thanks in advance!

In my React Mapbox GL component, I tried fetching GeoJSON data from a specific URL using the fetch API. After successfully fetching the data and updating the geojsonData state with the fetched data, I expected the map to update and render the GeoJSON features on the map. However, despite the geojsonData state being updated with the fetched data, the map did not update accordingly. Only the initial map was displayed, without any GeoJSON features.

I also tried hardcoding the GeoJSON data directly into the component to eliminate any potential issues with the data retrieval. Even with the hardcoded GeoJSON data, the map still didn't update to display the features.

I verified that the fetched GeoJSON data and the hardcoded data are valid and contain the necessary coordinates and properties for rendering the features on the map.

I'm unsure why the map is not updating with the fetched or hardcoded GeoJSON data. I suspect there might be an issue with how I'm rendering the data on the map or updating the map's state.

1 Answer 1

1

From this GitHub page of react-map-gl, someone explained that <Source> is a PureComponent. After the first render, it does not update unless props shallowly change, i.e. oldValue !== newValue. When you mutate your JSON data, it is still the same object, so the changes are not detected by React.

I had the exact same issue while trying to pass a geoJSON object saved in a React state. The solution that solves the problem is to set a different key and force a re-render of the <Source> component:

import React, { useState } from 'react';
import Map, { Source } from 'react-map-gl';

const MyMap = () => {
  const [geojson, setGeojson] = useState(initialGeojson);
  const [key, setKey] = useState(0);

  // Function to update GeoJSON
  const updateGeojson = (newGeojson) => {
    setGeojson(newGeojson);
    setKey(key + 1); // Increment key to force re-render
  };

  return (
    <Map {...viewport}>
      <Source id="my-data" type="geojson" data={geojson} key={key}>
        {/* Add your layers here */}
      </Source>
    </Map>
  );
};

Or you could also use a package like uuid to generate random keys for each re-render.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.