Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

difficulty with requestOptions #904

Open
Minte-grace opened this issue Dec 22, 2021 · 15 comments
Open

difficulty with requestOptions #904

Minte-grace opened this issue Dec 22, 2021 · 15 comments
Labels
enhancement New feature or request help wanted Extra attention is needed

Comments

@Minte-grace
Copy link

can anyone help with the correct way of passing location and radius to requestOptions I tried usePlacesAutocomplete({ requestOptions: { types: "address", radius: 500, location: { lat: 8.7, 38.8 } }, debounce: 300, }); but its not working

@wellyshen wellyshen added the help wanted Extra attention is needed label Jan 12, 2022
@gitmazzio
Copy link

Same problem.

@wellyshen
Copy link
Owner

wellyshen commented Jan 23, 2022

@Minte-grace Seems you lack the location.lng property?

usePlacesAutocomplete({
      requestOptions: {
        types: "address",
        radius: 500,
        location: {
          lat: 8.7,
+         lng: 38.8,
        },
      },
      debounce: 300,
    });

@Minte-grace
Copy link
Author

@wellyshen
yeah but the thing is, it aliases the suggestion but it doesn't strict to that location. I end up calling the places on the server-side and fetch the detail of the places using this library

@johnhaup
Copy link

what is not working?

@mduong
Copy link

mduong commented Mar 24, 2022

I'm also running into issues when trying to provide a the location option. By providing a location request option using the example in the README (https://github.com/wellyshen/use-places-autocomplete#create-the-component), autocomplete does not work. Typing into the input field does not successfully get any suggestions. If I remove location, however, things work again.

const {
    ready,
    value,
    suggestions: { status, data },
    setValue
  } = usePlacesAutocomplete({
    requestOptions: {
      location: { lat: 40.7127753, lng: -74.0059728 } // Having this causes autocomplete to not work
    }
  });

Oddly not seeing anything out of the ordinary in the console and logging status prints an empty string and never OK.

@wangela
Copy link

wangela commented Mar 25, 2022

Try also specifying a radius in the requestOptions. The location bias is defined as a circle with location as the center and radius in meters (max 50,000 meters).

@mduong
Copy link

mduong commented Mar 25, 2022

Try also specifying a radius in the requestOptions. The location bias is defined as a circle with location as the center and radius in meters (max 50,000 meters).

Ah yeah, I did try that as well but no luck.

@hossameldeen
Copy link

I'm also running into issues when trying to provide a the location option. By providing a location request option using the example in the README (https://github.com/wellyshen/use-places-autocomplete#create-the-component), autocomplete does not work. Typing into the input field does not successfully get any suggestions. If I remove location, however, things work again.

const {
    ready,
    value,
    suggestions: { status, data },
    setValue
  } = usePlacesAutocomplete({
    requestOptions: {
      location: { lat: 40.7127753, lng: -74.0059728 } // Having this causes autocomplete to not work
    }
  });

Oddly not seeing anything out of the ordinary in the console and logging status prints an empty string and never OK.

I had the same issue, but adding radius fixed it. Perhaps try clearing site data after adding radius? ... The library uses session storage for caching, so it might be causing an issue somehow.

image

Also, I've upgraded to v2.0.0, not sure if it makes a difference. And also, you may want to clear the site data after doing so.

(P.S: Make sure to clear the site data for localhost:3000 only. I once cleared site data for all websites by mistake or something, logging me out of all my accounts)

@mduong
Copy link

mduong commented Mar 30, 2022

Thanks @hossameldeen. Unfortunately, that also didn't work for me. I was only able to get it to work by passing an instance of LatLng like so:

const {
    ready,
    value,
    suggestions: { status, data },
    setValue
  } = usePlacesAutocomplete({
    requestOptions: {
      location: new window.google.maps.LatLng(40.7127753, -74.0059728),
      radius: 5000,
    }
  });

@hossameldeen
Copy link

When debugging the issue, I've found that loading remains true in case of an invalid input like missing radius or sending in a wrong type for location. My suspicion is that getPlacePredictions throws an error instead of calling the callback. In that case, loading remains true and we don't propagate the error to the library's user.

Here, we set loading: true:

setSuggestions((prevState) => ({ ...prevState, loading: true }));

If getPlacesPrediction throws an error instead of calling the callback in case of an invalid input, loading will remain true, and the library's user won't know that an issue has happened:

asRef.current.getPlacePredictions(
{ ...requestOptionsRef.current, input: val },
(data: Suggestion[] | null, status: Status) => {
setSuggestions({ loading: false, status, data: data || [] });
if (cache && status === "OK") {
cachedData[val] = {
data: data as Suggestion[],
maxAge: Date.now() + cache * 1000,
};
try {
sessionStorage.setItem(cacheKey, JSON.stringify(cachedData));
} catch (error) {
// Skip exception
}
}
}
);

A possible enhancement would be to try/catch the call getPlacesPrediction call and add the error to suggestions state somehow.

For now, if someone is facing a similar problem: console.log(loading). And if it remains true, the issue is probably that your arguments are invalid somehow. You can the review parameter types & constraints here.

@wellyshen
Copy link
Owner

wellyshen commented Mar 31, 2022

@hossameldeen That's wired, the callback supposes should be triggered even if there's an error because the callback is given a status argument. 🤔

@hossameldeen
Copy link

hossameldeen commented Mar 31, 2022

Summary: Strangely, when calling getPlacesPredictions in callback style with an invalid input, neither an error is thrown nor is the callback called. However, when using the Promise-based variant, we indeed receive an error in catch.

Original message:

@wellyshen Agreed, it's weird indeed.

  1. Take this even weirder info: It neither calls the callback nor throws an error in case of an input error 🤔
    Nothing is logged for this code:
const service = new google.maps.places.AutocompleteService();
    try {
      service.getPlacePredictions(
        {
          input: "restaurant",
          types: ["establishment"],
          location: new google.maps.LatLng({
            lat: 50,
            lng: 50,
          }),
          // radius: 123,
        },
        (predictions, status) => {
          console.log("In callback", predictions, status);
        }
      );
    } catch (e) {
      console.log("In catch", e);
    }
  1. However, there's hope: When using Promise-based calling, it does call catch.
    Code:
    service
      .getPlacePredictions({
        input: "restaurant",
        types: ["establishment"],
        location: new google.maps.LatLng({
          lat: 50,
          lng: 50,
        }),
        // radius: 123,
      })
      ?.then((predictions) => {
        console.log("In then", predictions);
      })
      .catch((e) => {
        console.log("In catch", e);
      });

Logs:
image

Update: Removed the point about status representing server errors only. The reference screenshot had "INVALID_REQUEST" as one of the possible values, actually.

@wellyshen
Copy link
Owner

wellyshen commented Apr 3, 2022

@hossameldeen Thank you for the detailed explanation. There's room for improving the error handling. Will spend time thinking about it. BTW, a PR for the error handling improvement is welcome as well.

@wellyshen wellyshen added the enhancement New feature or request label Apr 3, 2022
@cdslxc
Copy link

cdslxc commented May 20, 2022

Thanks @hossameldeen. Unfortunately, that also didn't work for me. I was only able to get it to work by passing an instance of LatLng like so:

const {
    ready,
    value,
    suggestions: { status, data },
    setValue
  } = usePlacesAutocomplete({
    requestOptions: {
      location: new window.google.maps.LatLng(40.7127753, -74.0059728),
      radius: 5000,
    }
  });

I'm using NextJS, load the script by next/script

<Script strategy="beforeInteractive" src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" />

I got ReferenceError: google is not defined

@MarioPerezDev
Copy link

Thanks @hossameldeen. Unfortunately, that also didn't work for me. I was only able to get it to work by passing an instance of LatLng like so:

const {
    ready,
    value,
    suggestions: { status, data },
    setValue
  } = usePlacesAutocomplete({
    requestOptions: {
      location: new window.google.maps.LatLng(40.7127753, -74.0059728),
      radius: 5000,
    }
  });

I'm using NextJS, load the script by next/script

<Script strategy="beforeInteractive" src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" />

I got ReferenceError: google is not defined

That is probably because you have not waited to the api to load and tried to read google before it has ended.

Also for those of you having problems, yes, as mentioned, the hook uses cache by default, so you might need to delete sessionstorage when you change the requestoptions (this could maybe be automatic somehow).

Lastly, radius and location are deprecated now, so for someone wondering how it should be done now, an option could be using a circle with a radius and using locationBias like so:

requestOptions: {
      locationBias: new google.maps.Circle({ {lat: 40.71960243832271, lng: -74.03454420585065}, 
      radius: 1000
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

9 participants