Home > Software design >  Server Error : TypeError: Cannot convert undefined or null to object
Server Error : TypeError: Cannot convert undefined or null to object

Time:10-27

Here is the Code

import { getProviders, signIn as SignIntoProvider } from "next-auth/react"

function signIn({ providers }) {
    return (
        <>
            {Object.values(providers).map((provider) => (
                <div key={provider.name}>
                    <button onClick={() => SignIntoProvider(provider.id)}>
                        Sign in with {provider.name}
                    </button>
                </div>
            ))}
        </>
    )
}

export async function getServerSideProps() {
    const providers = await getProviders();

    return {
        props: {
            providers
        }
    }
}

export default signIn

I am getting this error on pasting NextAuth.js sample code from the official website. I have the latest build of Node.js and Next.js.

You can find the whole source code here https://github.com/aadipoddar/instagram-react

CodePudding user response:

That's the result of the map function being called before providers actually has any value.
You can use conditional rendering to avoid such problems.

Try this:

{providers && providers.length && Object.values(providers).map((provider) => ( ...

You can make it look nicer by storing it in a variable.

Like so:

function signIn({ providers }) {
    const checkProviders = (
       providers &&
       providers.length
    );

    return (
        <>
            {checkProviders && Object.values(providers).map((provider) => (
                <div key={provider.name}>
                    <button onClick={() => SignIntoProvider(provider.id)}>
                        Sign in with {provider.name}
                    </button>
                </div>
            ))}
        </>
    )
}
  • Related