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;
};
>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;