1

I'm attempting to work with GoogleMapReact in a gatsby app and have run across a strange issue where I can't set state if the state is a Google Maps object...

import React, { useStat1e, useEffect, useRef } from 'react'
import GoogleMapReact from 'google-map-react';
const [ mapsObj, setMapsObj ] = useState(false)

const Map = () => {
    const [ mapsObj, setMapsObj ] = useState(false)

    const apiIsLoaded = (map, maps, places) => {
        console.log('maps', maps)
        setMapsObj(maps)
        console.log(mapsObj)
    }
}

...

Console responses:

maps {Animation: {…}, ControlPosition: {…}, __gjsload__: ƒ, BicyclingLayer: ƒ, Circle: ƒ, …}
null

If maps if set, why is setMapsObj not updating its state?

brunam
  • 825
  • 2
  • 14
  • 26
  • React state updates are asynchronously processed. The update you enqueued won't be available until the ***next*** render cycle. The console log of state can, and will, only ever log the state value from the ***current*** render cycle. – Drew Reese Jul 30 '21 at 23:36
  • The maps object is correctly set, you're just [logging at the wrong time](https://jsramblings.com/are-you-logging-the-state-immediately-after-updating-it-heres-why-that-doesnt-work/) - move the `console.log` right before the `return` statement and you'll see the right value :) – Corina Jul 31 '21 at 07:30

0 Answers0