Skip to content

How to return value in nested function React (navigator.geolocation.getCurrentPosition())

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.

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";

export const getGeolocation = createAsyncThunk(
  async () => {
    if (navigator.geolocation) {
      /*return */ navigator.geolocation.getCurrentPosition((position) => {
        //  ^^^^^^^^^^ I suggest that I should add return here ,
        // but it's still undefined, because this method return undefined anyway
        const { latitude, longitude } = position.coords;
        return { latitude, longitude }; // I understand that this won't work

What is the best way to solve this problem?



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:

export const getGeolocation = createAsyncThunk(
  () => { // this is the payload creator function
    //return a promise
    return new Promise((resolve, reject) =>
        ? reject('Geolocation not supported')
        : navigator.geolocation.getCurrentPosition(
            ({coords:{ latitude, longitude }}) =>
              resolve({ latitude, longitude }),
            reject //reject promise when there is an error
User contributions licensed under: CC BY-SA
3 People found this is helpful