Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Invalid hook call. Hooks can only be called inside of the body of a function component React,JS

hello everyone I have this call within a hooks I need the lat and lng variables to be saved in the state as I am currently doing it shows me the following error, I hope someone can help me
Error: Invalid hook call. Hooks can only be called inside the body of a function component. This could happen for one of the following reasons:

useEffect(() => {
    const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=.....`;
    const http = new XMLHttpRequest();
    http.open("POST", url);
    http.onreadystatechange = function(){
      if(this.readyState == 4 && this.status == 200){
       const data = JSON.parse(this.responseText);
       const {location: {lat, lng}} = data;
       const result = {lat, lng} ;
       const  [locations, setLocation] = useState({
            loaded: true,
            coordinates: {
                lat: result.lat,
                lng: result.lng,
            },
            aceptacion:1
        });
        console.log(setLocation);
       return result;
      }
    }
    http.send();
}, []);

return location;

};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Move useState initialization outside useEffect hook.

const [locations, setLocation] = useState({
    loaded: true,
    coordinates: null,
    aceptacion: null,
});

useEffect(() => {
    const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=.....`;
    const http = new XMLHttpRequest();
    http.open("POST", url);
    http.onreadystatechange = function(){
      if(this.readyState == 4 && this.status == 200){
       const data = JSON.parse(this.responseText);
       const {location: {lat, lng}} = data;
       const result = {lat, lng} ;
       setLocation({
            loaded: true,
            coordinates: {
                lat: result.lat,
                lng: result.lng,
            },
            aceptacion:1
        });
        console.log(setLocation);
        return result;
      }
    }
    http.send();
}, []);

return locations;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading