Next.js Discord

Discord Forum

"ReferenceError: google is not defined" with react-places-autocomplete

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
Hey hey, so we're migrating our project to nextjs 13 and I seem to be having some trouble correctly setting up my scripts...

Currently I'm trying to get our google places autocomplete component to function as I want it. I'm trying to include a searchOption that includes the lat and lng of the user to suggest more relevant locations, but I'm having some issues using the google.maps api.

In my root layout.tsx, I've included the following code
export default function RootLayout({
    children,
}: {
    children: React.ReactNode;
}) {
    return (
        <html
            lang='en'
            className={`${roboto_condensed.variable} ${roboto.variable} h-screen`}
        >
            <Head>
                <script src={process.env.NEXT_PUBLIC_MAPS_API} async defer />
            </Head>
            <body className='h-full bg-background'>
                <Background />
                <OrganizerWrapper />
                <ThemeProvider attribute='class' defaultTheme='system' enableSystem>
                    {children}
                </ThemeProvider>
                <Toaster />
            </body>
        </html>
    );
}


And inside my input component, I'm referencing it as such

const searchOptions = {
        bounds: new google.maps.LatLngBounds(
            new google.maps.LatLng(coordinates.lat, coordinates.lng)
        ),
    };


This is close to how we had it set up before, and judging by the next 13 conversion docs, I think I'm calling the script as best I can. All the discussion posts on stack and whatnot all seem to point to "The script isn't loading in properly", but I don't see how that could be?

on build I get the attached screenshot. It's likely a silly mistake somewhere, but with most of the conversations taking place on pre-next 13 frameworks, I'm having trouble debugging myself. Any suggestions much appreciated

1 Reply

Brown bear
Solved issue by creating a state variable for searchParams using useState and assiging it in a useEffect since the issue is being caused by trying to access google before the script or the rest of the component has loaded 😄