Skip to content

Add Promise based versions to usePlacesAutocompleteService #212

Open
@nzayatz14

Description

@nzayatz14

Hi @ErrorPro

Is there any way you could add Promise-based versions of placesAutocompleteService.current.getPlacePredictions and placesAutocompleteService.current.getQueryPredictions in your usePlacesAutocompleteService hook?

Currently they look like:

if (placesAutocompleteService.current && optionsArg.input)
        placesAutocompleteService.current.getPlacePredictions(
          {
            ...(sessionToken && autocompleteSession.current
              ? { sessionToken: autocompleteSession.current }
              : {}),
            ...options,
            ...optionsArg,
          },
          (r) => {
            setIsPlacePredsLoading(false);
            setPlacePredictions(r || []);
          }
        );

but they could be wrapped like this:

return new Promise((resolve, reject) => {
            if (placesAutocompleteService.current && optionsArg.input) {
                placesAutocompleteService.current.getPlacePredictions(
                    {
                        ...(sessionToken && autocompleteSession.current
                            ? { sessionToken: autocompleteSession.current }
                            : {}),
                        ...options,
                        ...optionsArg,
                    },
                    (r) => {
                        setIsPlacePredsLoading(false);
                        resolve(r || []);
                    }
                );
            } else if (!optionsArg.input) {
                reject(`Invalid "input" arg: ${optionsArg.input}`);
            } else {
                reject("Google places instance not yet loaded");
            }
        });

This way, users could use the usePlacesAutocompleteService hook inline with promises instead of having to listen to updates to the placePredictions variable inside of a useEffect like you have in your example:

useEffect(() => {
    // fetch place details for the first element in placePredictions array
    if (placePredictions.length)
      placesService?.getDetails(
        {
          placeId: placePredictions[0].place_id,
        },
        (placeDetails) => savePlaceDetailsToState(placeDetails)
      );
  }, [placePredictions]);

Thanks!
Nick

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions