Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda