reactjsreact-google-mapsrecompose

How to call another function from withHandlers?


I am trying to implement google maps in my app using react-google-maps package. In map, I am showing multiple Marker and used MarkerCluster.

Until now I have no issue and easily implemented from the doc. But now I want to show InfoWindow if the marker is clicked.

So, I thought of making a function to get the click event and pass the markerId, so I can call the API and get the relevant data for that marker and then put it in infowindow in a tabular manner.

Now, the problem I am facing is:

1) Calling onToggleOpen from onMarkerClick

2) how to set data in infowindow object in onMarkerClick

All this problem I am facing is because i am using HOC i.e recompose. I am used to Class implement but tried functional implement trying to make it purely stateless.

Reference link: https://tomchentw.github.io/react-google-maps/#infowindow

Following is my code:

import React, { Component } from "react";
import Header from "./Header.js";
import Sidebar from "./Sidebar.js";
import axios from "axios";
import imgmapcluster from "./pins/iconmapcluster.png";
import user from "./pins/user1copy.png";
import { compose, withProps, withHandlers } from "recompose";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  InfoWindow
} from "react-google-maps";
// const fetch = require("isomorphic-fetch");
const {
  MarkerClusterer
} = require("react-google-maps/lib/components/addons/MarkerClusterer");

const MapWithAMarkerClusterer = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=AIzaSyCHi5ryWgN1FcZI-Hmqw3AdxJQmpopYJGk&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `90vh` }} />,
    mapElement: <div style={{ height: `100%` }} />
  }),
  withHandlers(
    {
      onMarkerClustererClick: () => markerClusterer => {
        // console.log("markerCluster", markerClusterer);
        const clickedMarkers = markerClusterer.getMarkers();
        // console.log(`Current clicked markers length: ${clickedMarkers.length}`);
        // console.log(clickedMarkers);
      },
      onMarkerClick: (props) => markerss => {


        //calling api and setting info window object
         props.isOpen=!props.isOpen //showing error 

      },
      onToggleOpen: ({ isOpen }) => () => ({
        isOpen: !isOpen
      })
    }
  ),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap
    defaultZoom={5}
    defaultCenter={{ lat: 22.845625996700075, lng: 78.9629 }}
    >
    <MarkerClusterer
      onClick={props.onMarkerClustererClick}
      averageCenter
      styles={[
        {
          textColor: 'white',
          url: imgmapcluster,
          height: 68,
          lineHeight: 3,
          width: 70
        }

      ]}
      enableRetinaIcons
      gridSize={50}
    >
      {props.markers.map((marker, index) => (
        <Marker
          key={index}
          icon={user}
          onClick={props.onMarkerClick.bind(props,marker)}
          position={{ lat: marker.latitude, lng: marker.longitude }}
        />
      ))}
      {props.isOpen && (
        <InfoWindow
          // position={{ lat: props.infowindow.lat, lng: props.infowindow.lng }}
          onCloseClick={props.onToggleOpen}
        >
          <h4>hello</h4>
        </InfoWindow>
      )}
    </MarkerClusterer>
  </GoogleMap>
));

class DemoApp extends React.PureComponent {
  componentWillMount() {
    this.setState({ markers: [],isOpen:false,infowindow:{} });
  }

  componentDidMount() {

    axios({
      url: "http://staging.clarolabs.in:6067/farmerinfo/farmercoordinates",
      method: "POST",
      data: {
        temp: "temp"
      },
      headers: {
        "Content-Type": "application/json"
      }
    }).then(res => {

      this.setState({ markers: res.data.data.list });
    });

  }

  render() {
    return <MapWithAMarkerClusterer markers={this.state.markers} isOpen={this.state.isOpen} InfoWindowobject={this.state.InfoWindowobject}/>;
  }
}

Solution

  • In order to call a withHandler from another, you need to separate them within two handlers. Also you can make use of withStateHandler and store the infoWindow state

    withStateHandlers(
        { infoWindow: null },
        {
          setInfoWindow: () => (value) => ({ infoWindow: value)
        }
    ),
    withHandlers({
      onToggleOpen: ({ isOpen }) => () => ({
            isOpen: !isOpen
      })
    }),
    withHandlers(
        {
          onMarkerClustererClick: () => markerClusterer => {
            // console.log("markerCluster", markerClusterer);
            const clickedMarkers = markerClusterer.getMarkers();
            // console.log(`Current clicked markers length: ${clickedMarkers.length}`);
            // console.log(clickedMarkers);
          },
          onMarkerClick: (props) => markerss => {
            const { setInfoWindow, onToggleOpen} = props;
    
            //calling api and setting info window object
            setInfoWindow({lat: res.lat, lng: res.lng}) // set infoWindow object here
            onToggleOpen() // Toggle open state
    
    
          }
        }
      ),