Set state with React and geolocation
Problem
I'm working with geolocation via navigator.geolocation
and got stuck trying to set state. The below code results in a TypeError: setState is undefined. I think this is because the this
keyword has taken on the function context because of the nested success
function.
state = {
coords: {},
}
handleGeoSubmit = event => {
event.preventDefault();
function success(position) {
let coords = position.coords;
// Throws TypeError 'setState' of undefined.
this.setState({
coords: coords
})
}
navigator.geolocation.getCurrentPosition(success, error, options);
};
Solution #1
Pass the function directly as an argument to retain 'this' global context.
navigator.geolocation.getCurrentPosition(
// Put function logic here.
(success = position => {
event.preventDefault();
let coords = position.coords;
// 'this' uses global context.
this.setState({ coords });
}),
error,
options
);
Solution #2
Create a variable with global context, then call that variable to Set State.
handleGeoSubmit = event => {
let context = this; // Declare global context of 'this' here.
event.preventDefault();
let options = {
timeout: 5000,
maximumAge: 0
};
function success(position) {
let coords = position.coords;
// Call the global 'context' here.
context.setState({
coords: coords
});
}