0

ReactJS newbie question. Can someone please enlighten me as to why inputValue.length in the code snippet below is 0 even after I use setInputValue() to set inputValue equal to a string. Note that the input field for which inputValue corresponds does indeed populate with the location string upon using setInputValue(). Any help is greatly appreciated!

const [inputValue, setInputValue] = React.useState('');

const getLocation = () => {
        if ("geolocation" in navigator) {
            navigator.geolocation.getCurrentPosition(function (position) {               

                (async () => {
                    const location = await Geocoder(position.coords.latitude,position.coords.longitude);                   
                    setInputValue(`${location}`);
                    console.log(inputValue.length);                                      
                })()
            });
        };
    };

 React.useEffect(() => {
        getLocation();            
 }, []);
sybercoda
  • 495
  • 3
  • 6
  • 24
  • 1
    In React, state updates are processed asynchronously, so when you console log state like this you are only logging the value from the ***current*** render cycle, not what it will be on the ***next*** render cycle. Use an `useEffect` hook with appropriate dependency to log state updates, i.e. `useEffect(() => console.log(inputValue.length), [inputValue]);`. – Drew Reese Jun 25 '21 at 22:01
  • Thanks @Drew. I also tried logging the value length in the useEffect as shown in the code snippet but had the same result. But I do have another useEffect in my component (not shown here), which is similar to your example and the input length there logs as intended. The useEffect in this provided code snippet has an empty array so that it only fires once since it initiates a web browser share your location prompt to the user. I wasn't aware of [inputValue] being required in order to get the latest state. Thanks again! – sybercoda Jun 25 '21 at 22:24

0 Answers0