1

I am trying to user Direction service of @react-google-maps/api.

I am using reactjs and doc link is https://react-google-maps-api-docs.netlify.app/#directionsservice.

 {response !== null && (
                <DirectionsRenderer
                  // required
                  options={{
                    directions: response
                  }}
                />
              )}

What am I doing wrong. I am not getting either.

response of the direction service

Monish N
  • 330
  • 1
  • 6
  • 15

1 Answers1

0

Map is getting rendered so many times. As per the documentation they are setting the state during render. render should always remain pure. It's a very bad practice to do side-effecty things in render and in some other react life cycle hook.

I think they have to work on improving the documentation. if we follow the documentation it will give direction but you will get an exceeded google maps quota error.

 const [response, setResponse] = React.useState(null);
   const directionsCallback = res => {
       console.log(' => res', res);
    if (res !== null) {
      if (res.status === 'OK') {
        setResponse(res);
      } else {
        console.log('res: ', res);
      }
    }
  };

         <DirectionsService
            options={{
              destination: destination,
              origin: origin,
              travelMode: 'DRIVING'
            }}
            callback={directionsCallback}
          />

Update:

This solved multiple rendering

let count = React.useRef(0);

const directionsCallback = React.useCallback(res => {
    console.log(count.current);
    if (res !== null) {
      if (res.status === 'OK' && count.current < 2) {
        count.current += 1;
        setResponse(res);
      } else {
        count.current = 0;
        console.log('res: ', res);
      }
    }
  }, []);
Monish N
  • 330
  • 1
  • 6
  • 15