React-Redux turn google places api into a promise Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of React-Redux turn google places api into a promise without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am kind of new to the react / redux stack and have a question about how to send the data I am getting from the google place api from an action to a reducer.

From the tutorial I followed, on the action level, I send a promise to the reducer, and react-promise handles this and save the promise/data in the state. (this might not be the best approach but as I said, I am kind of new to this stack and I am trying to follow what I have learned so far)

Here is my action:

export const FETCH_RESTAURANTS = 'FETCH_RESTAURANTS';

export function fetchRestaurants(lat = '51.5033640', lon = '-0.1276250') {

 var pyrmont = new google.maps.LatLng(lat,lon);

 const map = new google.maps.Map(document.getElementById('map'), {
   center: pyrmont,
   zoom: 15
 });

 var request = {
   location: pyrmont,
   radius: '500',
   query: 'restaurant',
   types: ['restaurant']
 };

 const service = new google.maps.places.PlacesService(map);
 service.nearbySearch(request, function(a, b) {
   console.log('here', a, b);
 });

 return {
  type: FETCH_RESTAURANTS,
  payload: ????
 };
}

From this code, the nearbySearch seems to do the job as it shows a list of restaurants in the console. But I don’t really understand how I can access this data outside the callback and return it to the reducer so it can be saved in my states.

Just in case, that is how I did it with a promise on a axios call, which worked and which is what I am trying to do:

export const FETCH_WEATHER = 'FETCH_WEATHER';
export function fetchWeather(city) {
 const url = `${ROOT_URL}&q=${city},us`;
 const request = axios.get(url);

 return {
   type: FETCH_WEATHER,
   payload: request
 };
}

Answer

You have to use an async library that handles async calls. one of the common library used is redux thunk.

export function fetchRestaurants(lat = '51.5033640', lon = '-0.1276250') {
    return (dispatch) => {

        ...

        service.nearbySearch(request, function(a, b) {
            console.log('here', a, b);
            dispatch(setNearbySearchResult(a,b));
        });
    }
}

function setNearbySearchResult(a,b) {
    return {
        type: FETCH_RESTAURANTS,
        payload: {a,b}
    };
}
// call this function in componentDidMount

dispatch(fetchResturants(lat,long))
We are here to answer your question about React-Redux turn google places api into a promise - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji