Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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(
  "weather/getGeolocation",
  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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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(
  'weather/getGeolocation',
  () => { // this is the payload creator function
    //return a promise
    return new Promise((resolve, reject) =>
      !navigator.geolocation
        ? reject('Geolocation not supported')
        : navigator.geolocation.getCurrentPosition(
            ({coords:{ latitude, longitude }}) =>
              resolve({ latitude, longitude }),
            reject //reject promise when there is an error
          )
    );
  }
);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!