reactjsgoogle-map-reactswr

Ternary operator doesn't work as expected


I have a map component where I need to pass default coordinates which will be coming from custom useSwr hook. After fetching the data I pass them to the state and render it if the values or not undefined. Apparently I do something wrong and its not working properly since Map component is being called even when the values are undefined which results in me getting this error:

Failed prop type: Invalid prop `center` supplied to `o`. 

This is how I handle state:

const {
    locationDetails,
    locationSessions,
    isLoading,
    isError,
  } = useLocations();

  const [mapCenter, setMapCenter] = useState({ lat: null, lng: null });
  useEffect(() => {
    setMapCenter({
      lat: locationDetails?.location_lat,
      lng: locationDetails?.location_lon,
    });
  }, [locationDetails]);

on render:

{mapCenter?.lat !== undefined &&
                    mapCenter?.lng !== undefined ? (
                      <GoogleMapReact
                        bootstrapURLKeys={{
                          key: "My api key",
                        }}
                        center={mapCenter}
                        zoom={14}
                      >
                        <IconMaps
                          name="PinDefault"
                          width="21px"
                          height="31px"
                          lat={parseFloat(location_lat)}
                          lng={parseFloat(location_lon)}
                        />
                      </GoogleMapReact>
                    ) : null}                     
                      

Solution

  • So you're saying that if you do this

    {mapCenter?.lat != undefined && // non-strict
                        mapCenter?.lng != undefined ? ( // non-strict
                          <GoogleMapReact
                            bootstrapURLKeys={{
                              key: "My api key",
                            }}
                            center={mapCenter}
                            zoom={14}
                          >
                            <IconMaps
                              name="PinDefault"
                              width="21px"
                              height="31px"
                              lat={parseFloat(location_lat)}
                              lng={parseFloat(location_lon)}
                            />
                          </GoogleMapReact>
                        ) : null}                     
                          
    

    It still returns the map? Try returning something else apart from null (like a piece of text, just for testing purposes), because I feel like there may be other problems than the ternary.