I want to add weather by geolocation into my React+Redux app. I found that I can get geolocation by this JS method navigator.geolocation.getCurrentPosition(success, error, [options]). I want to dispatch that to my Redux weatherSlice, but this method returns undefined by default so I can’t dispatch it by createAsyncThunk.
JavaScript
x
16
16
1
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
2
3
export const getGeolocation = createAsyncThunk(
4
"weather/getGeolocation",
5
async () => {
6
if (navigator.geolocation) {
7
/*return */ navigator.geolocation.getCurrentPosition((position) => {
8
// ^^^^^^^^^^ I suggest that I should add return here ,
9
// but it's still undefined, because this method return undefined anyway
10
const { latitude, longitude } = position.coords;
11
return { latitude, longitude }; // I understand that this won't work
12
});
13
}
14
}
15
);
16
What is the best way to solve this problem?
Advertisement
Answer
The getCurrentPosition method probably only works on https or localhost.
The payloadCreator function of crateAsyncThunk should return a Promise, you can convert a callback type function to a promise.
In your code it would look like this:
JavaScript
1
16
16
1
export const getGeolocation = createAsyncThunk(
2
'weather/getGeolocation',
3
() => { // this is the payload creator function
4
//return a promise
5
return new Promise((resolve, reject) =>
6
!navigator.geolocation
7
? reject('Geolocation not supported')
8
: navigator.geolocation.getCurrentPosition(
9
({coords:{ latitude, longitude }}) =>
10
resolve({ latitude, longitude }),
11
reject //reject promise when there is an error
12
)
13
);
14
}
15
);
16