Search code examples
reactjsmapboxmapbox-gl-jsreact-componentreact-map-gl

How to setState of one state using the state of another state onClick


Is there a way to setState of one state with the state of another state? For example below in _updateData()...on click the geojson state gets the state of newGeojson? The goal is to be able to change the data={geojson} on click of the button (not showing the Geojson files in the example but let's say they exist in GeoJSON and newGeojson. I pull JSON from a firebase then convert it to GeoJSON in componentDidMount to create the geojson states). Thanks for the help. Hopefully, I am approaching this the right way.

import React from 'react';
import ReactMapGL, {Source, Layer} from 'react-map-gl';

class Map extends React.Component {
  state = {
    geojson: null,
    newGeojson: null,
  };

  _updateData() {
    // In here set the state of geojson to the state of newGeojson so the data={geojson} updates on click, something like setState{geojson} = newGeojson
  }

  render() {
    const {geojson} = this.state;

    return (
      <ReactMapGL latitude={37.78} longitude={-122.41} zoom={8}>
        <Source id="my-data" type="geojson" data={geojson}>
          <Layer
            id="point"
            type="circle"
            paint={{
              'circle-radius': 10,
              'circle-color': '#007cbf'
            }} />
        </Source>
        <button onClick={this._updateData()}>Update</button>
      </ReactMapGL>
    );
  }
}

Solution

  • Like that:

    import React, { useState } from 'react';
    import ReactMapGL, {Source, Layer} from 'react-map-gl';
    
    const Map = () => {
      const [geojson, setGeojson] = useState(null)
    
      const updateData = () => {
        // for example
        fetch('url').then(resp => resp.json()).then(resp => {
          setGeojson(resp.data)
        })
      }
    
      return (
        <ReactMapGL latitude={37.78} longitude={-122.41} zoom={8}>
          <Source id="my-data" type="geojson" data={geojson}>
            <Layer
              id="point"
              type="circle"
              paint={{
                'circle-radius': 10,
                'circle-color': '#007cbf'
              }} />
          </Source>
          <button onClick={updateData}>Update</button>
        </ReactMapGL>
      );
    }
    

    It's using hooks. For old syntax you probably want this.setState({geojson: newGeojson}) (https://reactjs.org/docs/react-component.html#setstate)