im a little stuck. Im trying to store the user coordinates from the componentDidMount in the handlesubmit as a const however whenever i try to I'll get an error. The error i'm getting is : 'position' is not defined no-undef. Any way i could go about storing the position as a const so i could access it in the handlesubmit part?
Thanks Code is below
componentDidMount() {
navigator.geolocation.getCurrentPosition(function(position ) {
const { latitude, longitude } = position.coords;
console.log(position )
console.log(latitude)
console.log(longitude)
});
}
handleSubmit = (event) => {
const productName = document.querySelector('#productName') .value.trim();
const productCondition = document.querySelector('#productCondition') .value.trim();
const productDescription = document.querySelector('#productDescription') .value.trim();
const productLocation = position
console.log(productLocation )
const data = 'productName=' encodeURIComponent(productName) '&productCondition=' encodeURIComponent(productCondition) '&productDescription=' encodeURIComponent(productDescription);
alert('A form was submitted: ' data);
fetch('api url', {
method: 'POST',
mode: "no-cors",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
// body: JSON.stringify(this.state)
body: data
}).then(function(response) {
console.log(response.text)
/*return response.json();*/
});
event.preventDefault();
}
CodePudding user response:
Its simple
const getPosition = function () {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
}
getPosition()
.then(position => {
console.log(position);
sessionStorage.setItem('position', position);
)
.catch(error => {
console.error(error);
}
Use the variable position in the sessionStorage:
const data = sessionStorage.getItem('position');
Or you can use useState
CodePudding user response:
You can use useState.
import React from "react"
class Welcome extends React.Component {
state = {
lat: 0,
lng: 0
}
componentDidMount() {
let latitude = 0;
let longitude = 0;
let success = position => {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
this.setState(
{
lat: latitude,
lng: longitude
},
);
};
function error() {
console.log("Unable to retrieve your location");
}
navigator.geolocation.getCurrentPosition(success,error )
}
handleSubmit = (event) => {
event.preventDefault();
const productLocation = this.state
console.log(productLocation )
}
render() {
return <h1>Hello, {this.props.name} </h1> ;
}
}
export default Welcome;