Search code examples
javascriptreactjsobjectreact-hooksref

Javascript object show null but after click to see there are value but cannot access


I am developing the project by using ReactHook and I have problem with React.createRef(). I suffer this problem and I want to know what is the situation like this called? and how to fix it? As in the figure 1, it shows that the value of the object is null but when I click to see it. There are value there but I cannot access its value by the key because I cannot access the key of null. Figure 1.After I tried to <code>console.log</code> variable googleMap
Figure 1.After I tried to console.log variable googleMap

import { Map, GoogleApiWrapper } from "google-maps-react";
import { GOOGLE_API_KEY } from "../../key.js";

const storePage = ({google}) => {
  const googleMap = React.createRef();
  console.log(googleMap.current.map);
  ...

Figure 2.I just use React.createRef() in order to access component

...
return (
<Map
            google={google}
            zoom={16}
            initialCenter={{ lat: yourLocation.lat, lng: yourLocation.lng }}
            style={{ height: "20rem" }}
            ref={googleMap}
          ></Map>)
}
const enhance = compose(
  GoogleApiWrapper({ apiKey: GOOGLE_API_KEY }),
  connect(mapStateToProps, mapDispatchToProps)
);

export default enhance(StorePage);

Figure 3.I want to access the component for getting the value like figure 1
Figure 4.But when I access the value by the key(like this <code>googleMap.current.map</code>), the error occurs like this figure
Figure 4.But when I access the value by the key(like this googleMap.current.map), the error occurs like this figure


Solution

  • import React, {useEffect, useRef} from 'react';
    
    const googleMap = useRef(null);
    
    useEffect(() => {
        console.log(googleMap && googleMap.currentValue)
    }, [googleMap])
    

    Notice I used the hook for creating the ref. What this will do is run a use effect whenever the value of the googleMap ref changes. IE: Before and after the ref is rendered.