Chaitra Katoti
Chaitra Katoti

Reputation: 131

Reference Error:Navigator not defined with nextjs

My code is like this:

import React, { useEffect } from 'react';

    import alanBtn from '@alan-ai/alan-sdk-web';
    
    const alanKey = my key;
    const App = () => {
        useEffect(() => {
            alanBtn({
                key: alanKey,
                onCommand: ({ command }) => {
                        alert('This code was executed');
                }
            })
        }, []);
        return (
            <div><h1>Alan AI News Application</h1></div>);
    }
    export default App;

But I am making the error as:

Reference Error:Navigator not defined..

What is the solution?

Upvotes: 11

Views: 28324

Answers (3)

GorvGoyl
GorvGoyl

Reputation: 49150

Browser objects like window , navigator etc should be defined in useEffect first before use.

  const [pageURL, setPageURL] = useState("");
  const [isNativeShare, setNativeShare] = useState(false);
  useEffect(() => {
    setPageURL(window.location.href);
    if (navigator.share) {
      setNativeShare(true);
    }
  }, []);

// Now, you can use pageURL, isNativeShare in code

Upvotes: 23

Hiago Le&#227;o
Hiago Le&#227;o

Reputation: 11

Sometimes the page is pre-rendered on the server and the navigator variable is not declared there. Before calling anything that has the navigator variable, you should check that the code is running in the browser.

import { platform } from 'os';

if (platform() !== 'browser') return;
console.log('This is your navigator: ', navigator);

Upvotes: 1

Ujwal Agrawal
Ujwal Agrawal

Reputation: 474

This is not an issue with your Next.js code it's just the way you are supposed to call the alan-ai library.

Below is the solution that should work for you.

import React, { useEffect } from "react";

const alanKey = "my key";
function App() {
useEffect(() => {
   const alanBtn = require("@alan-ai/alan-sdk-web");
   alanBtn({
   key: "myKey",
   rootEl: document.getElementById("alan-btn")
  });
}, []);

return (
 <div>
  <h1>Alan AI News Application</h1>
 </div>
 );
}
export default App;

Here is the discussion link for the same https://github.com/alan-ai/alan-sdk-web/issues/29#issuecomment-672242925.

Hope this solves your issue.

Happy Coding.

Upvotes: 2

Related Questions