question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Next.js Integration

See original GitHub issue

I would appreciate a definitive guide on using this with next.js. The Next.js script tag with a beforeInteractive strategy gives the error use-places-autocomplete: Google Maps Places API library must be loaded. The native script tag only works with asynchronous loading since external synchronous scripts are forbidden in Next.js. asynchronously loading the script occasionally freezes the input field.

Issue Analytics

  • State:open
  • Created a year ago
  • Reactions:9
  • Comments:9

github_iconTop GitHub Comments

2reactions
DopamineDrivencommented, Jul 12, 2022

Per the recent Nextjs shift in best practices for loading beforeInteractive scripts, you can instantiate the library as pictured and it works perfectly. I’m using next@latest, edge middleware, etc etc; works with next@12.x.x AA66211F-B6D6-49DC-85FB-90708DD14C6A

if anyone has tips for using the returned latlng values with Algolia InstantSearch Hooks it’d be much appreciated. I currently have it all working in isolation; but when using both Google places and algolia in the same form the fetching strategies clash I think (fiddling with Promise.all([]) but might say fuck it and use global context, keep the worlds separate).

That said, it would be dope to see an algolia-instantsearch-hooks use places autocomplete integration 4ED8D13C-9C3E-4A1F-88C6-5611F3A8B35A

0reactions
nyfever007commented, Dec 12, 2022

@paularah By using use-google-maps-script package you can wait until script is loaded then call your address component.

import { Libraries, useGoogleMapsScript } from 'use-google-maps-script';
const libraries: Libraries = ['places'];
const App = () => {
  const { isLoaded, loadError } = useGoogleMapsScript({
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOLGE_MAPS_API_KEY!,
    libraries,
  });
return(
 <div>
  {isLoaded && (
          <AutoPlacesAddress setSelectedAddress={setSelectedAddress}    defaultValue={null}  />
        )}
</div>
  )
}
export default App
import { useRef } from 'react';
import usePlacesAutocomplete, {  getDetails,  getGeocode,  getLatLng,} from 'use-places-autocomplete';
import { useOnClickOutside } from 'usehooks-ts';

type Props = {  setSelectedAddress: React.Dispatch<React.SetStateAction<AddressFormValues>>;
  defaultValue: string | null;};
const AutoPlacesAddress = ({ setSelectedAddress, defaultValue }: Props) => {
  const {
    ready,
    value,
    suggestions: { status, data },
    setValue,
    clearSuggestions,
  } = usePlacesAutocomplete({
    requestOptions: {
      /* Define search scope here */
    },
    debounce: 500,
  });
  const handleInput = (e: React.ChangeEvent<HTMLInputElement>): void => {
    setValue(e.target.value);
  };
  const ref = useRef(null);
  const handleClickOutside = () => {
 // use useOnClickOutside hook to close the suggestions when user clicks outside of the component
    clearSuggestions();
  };
  useOnClickOutside(ref, handleClickOutside);
  const handleSelect =
    (suggestion: { description: string; place_id: string }) => async () => {
      // When user selects a place, we can replace the keyword without request data from API
      // by setting the second parameter to "false"
      setValue(suggestion.description, false);
      const placeId = {
        placeId: suggestion.place_id,
      };
      clearSuggestions();
      try {
       const latlng = await getGeocode({ address: suggestion.description });
        const { lat, lng } = getLatLng(latlng[0]);
        const detail: any = await getDetails(placeId);
           setSelectedAddress({
          address: suggestion.description,
          lat: lat,
          lng: lng,
        });
      } catch (error) {
        console.log(error);
      }
    };
  const renderSuggestions = () =>
    data.map((suggestion) => {
      const {
        place_id,
        structured_formatting: { main_text, secondary_text },
      } = suggestion;
      return (
        <li
          key={place_id}
          onClick={handleSelect(suggestion)}
          className='w-full cursor-pointer border-b py-1 px-4  last-of-type:border-0 hover:bg-indigo-500 hover:text-white'
        >
          <div>
            {main_text} <small>{secondary_text}</small>
          </div>
        </li>
      );
    });


  return (
    <>
      <div ref={ref} className='relative'>
        <input
          value={value}
          onChange={handleInput}
          disabled={!ready}
          placeholder={defaultValue!}
          className='form-input w-full rounded-md border-neutral-300 outline-none focus:border-dark-900 focus:outline-0 focus:ring-0'
        />
        {/* We can use the "status" to decide whether we should display the dropdown or not */}
        {status === 'OK' && (
          <ul className='absolute top-10 w-full rounded-md border bg-neutral-50'>
            {renderSuggestions()}
          </ul>
        )}
      </div>
    </>
  );
};
export default AutoPlacesAddress;
Read more comments on GitHub >

github_iconTop Results From Across the Web

Advanced Features: Custom Server - Next.js
A custom Next.js server allows you to start a server 100% programmatically in order to use custom server patterns. Most of the time,...
Read more >
Testing | Next.js
Learn how to set up Next.js with three commonly used testing tools — Cypress, Playwright, Jest, and React Testing Library.
Read more >
Getting Started | Next.js
Get started with Next.js in the official documentation, and learn more about all our features!
Read more >
next/server - Next.js
next /server provides server-only helpers for use in Middleware and Edge API Routes. NextRequest. The NextRequest object is an extension of the native...
Read more >
Deployment - Next.js
This document will show how to deploy either managed or self-hosted using the Next.js Build API. Next.js Build API. next build generates an...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found