0

I'm using react-places-autocomplete package, with the function geocodeByAddress. It should return the coordinates of an address, if the search action is triggered.

Here i my code:

export function handleSearch(address){
    console.log("handleSearch searching for address: " + address )
    var LAT = '';
    var LNG = '';
    const request = geocodeByAddress(address,  (err, { lat, lng }, result) => {
        var res = "";
        if (err) {
            console.log('Oh no!', err);
            res = 'Oh no! Something went wrong :(';
        } else {
            console.log(
                `iYay! got latitude and longitude for ${address}`, { lat, lng });
            res = `Yay! got latitude and longitude for ${address}: ${lat}, ${lng}`;
        }
        LAT = lat;
        LNG = lng;
        console.log(result);
    });
    console.log("request", request);
    return {
        type: 'SEARCH_EVENT',
        payload: {"lat": LAT, "lng": LNG}
    };

}

I know it does not work, because as I undestand geocodeByAddress is async and the callback function is executed later. How to deal with that? I know that it would be nice to use react-pormise with axioms but in this case I don't have a promise.

Thanks and best regrads.

1
  • Came up with the idea calling handleSearch from geocodeByAddress in the container. But still not sure if this is a good solution. Commented Apr 3, 2017 at 20:38

1 Answer 1

1

Look into redux-thunk. It lets you handle asynchronous actions very easily.

export function handleSearch(address){
    return (dispatch) => {
        console.log("handleSearch searching for address: " + address )
        var LAT = '';
        var LNG = '';
        const request = geocodeByAddress(address,  (err, { lat, lng }, result) => {
            var res = "";
            if (err) {
                console.log('Oh no!', err);
                res = 'Oh no! Something went wrong :(';
            } else {
                console.log(
                    `iYay! got latitude and longitude for ${address}`, { lat, lng });
                res = `Yay! got latitude and longitude for ${address}: ${lat}, ${lng}`;
            }
            LAT = lat;
            LNG = lng;
            console.log(result);

            dispatch({
                type: 'SEARCH_EVENT',
                payload: {"lat": LAT, "lng": LNG}
            });
        });

        console.log("request", request);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.