Reference Error:Navigator not defined with nextjs

Viewed 11036

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 getting the error as: Reference Error:Navigator not defined.. How to fix it?

2 Answers

Browser objects like window , navigator etc should be define 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, use can use pageURL , isNativeShare in code

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.

Related