0

I have two snips listed below, namely sagas.js and mapUpdates.js

For some reason in the saga.js file the var venues = yield getVenueCoords() line does not wait for the request to complete, which in turn setUserCoords(venues) in my redux store as undefined.

If I put at the end of the request statement, in the function, console.log(JSON.parse(body)), then at the end of the setup, after all other functions have run in my saga, I have the json logged to console.

I need to have the request finish before moving onto the setVenueCoords(venues) to properly update the store with venue data.

What am I doing wrong here, and what can I do to fix it ?

sagas.js

import { put, takeEvery, all } from "redux-saga/effects";
import { delay } from "redux-saga";
import { getPreciseLocation, getVenueCoords } from "../utils/mapUpdates";
import {
  setUserCoords,
  setVenueCoords,
  initMapRunning,
  initMapComplete
} from "../actions";

function* initMap() {
  var userLocation = {};
  var userCoords = yield getPreciseLocation().then(function(value) {
    return (userLocation = { lat: value[0], lng: value[1] });
  });
  yield put(setUserCoords(userCoords));
  yield delay(3000);
  var venues = yield getVenueCoords(userCoords);
  yield put(setVenueCoords(venues));
  yield put(initMapComplete());
}

function* watchInitMap() {
  yield takeEvery("INIT_MAP", initMap);
}

export default function* rootSaga() {
  yield all([watchInitMap()]);
}

mapUpdates.js

export function getVenueCoords(userCoords) {
  let obj = request(
    {
      url: "https://api.foursquare.com/v2/venues/explore",
      method: "GET",
      qs: {
        client_id: foursquareID,
        client_secret: foursquareSecret,
        ll: userCoords,
        query: "coffee",
        v: "20171114",
        limit: 10000
      }
    },
    function(err, res, body) {
      if (err) {
        console.error(err);
      } else {
        return JSON.parse(body);
      }
    }
  );
}
Aran Freel
  • 3,085
  • 5
  • 29
  • 42

1 Answers1

0

I found the best way to approach this is to use the bluebird library and simply to promisify the request.

It can be found how to do it at this link . . .

How do you properly promisify request?

var request = Promise.promisify(require("request"), {multiArgs: true});
Promise.promisifyAll(request, {multiArgs: true})

export function getVenueCoords(userCoords) {
  let obj = request(
    {
      url: "https://api.foursquare.com/v2/venues/explore",
      method: "GET",
      qs: {
        client_id: foursquareID,
        client_secret: foursquareSecret,
        ll: userCoords,
        query: "coffee",
        v: "20171114",
        limit: 10000
      }
    }).then(function(){})
Aran Freel
  • 3,085
  • 5
  • 29
  • 42