Next.js Discord

Discord Forum

Pass in next-auth session via function

Unanswered
Yellowstripe scad posted this in #help-forum
Open in Discord
Yellowstripe scadOP
how do I pass in the next-auth function?
    const { data: session, status } = useSession();
    const router = useRouter()
    if (!(status === "loading")) {
        if (!session) {
            router.push("/sign-in")
        }
    }
    const Voted = hasVoted(session)


I have a type named "Session" that works, I just don't know how to pass it in

I get this error:
Argument of type 'Session | null' is not assignable to parameter of type '{ session: Session; }'.
  Type 'null' is not assignable to type '{ session: Session; }'.ts(2345)


this is how I receive it:
export default async function hasVoted({session}: {session: Session}) {

67 Replies

Giant panda
try this
export default async function hasVoted({session}: {session: Session|null}) {}
@Giant panda try this js export default async function hasVoted({session}: {session: Session|null}) {}
Yellowstripe scadOP
export default async function hasVoted({session}: {session: Session}) {
    const foundUser = await db.user.findUnique({
        where: { username: (session?.user as any).username },
    });
    if (!foundUser) {
        return null
    }
    return foundUser.votedFor
}

my function was working right before
I just need to change something about passing it, not receiving it (if possible)
is it..?
Giant panda
so you're getting some typescript errors or something else ?
@Giant panda so you're getting some typescript errors or something else ?
Yellowstripe scadOP
const Voted = hasVoted(session)

session here is giving me this error when I hover over it:
Argument of type 'Session | null' is not assignable to parameter of type '{ session: Session; }'.
  Type 'null' is not assignable to type '{ session: Session; }'.ts(234
and when I put in what you gave me I get this one
Giant panda
session can be null too
Yellowstripe scadOP
Argument of type 'Session | null' is not assignable to parameter of type '{ session: Session | null; }'.
  Type 'null' is not assignable to type '{ session: Session | null; }'.ts(2345)
Giant panda
you should add some check for it
@Giant panda you should add some check for it
Yellowstripe scadOP
here/
?
if I add that, it doesnt change anything
Giant panda
export default async function hasVoted({ session }: { session: Session | null }) {
  if (!session?.user?.username) {
    return null; 
  }

  try {
    const foundUser = await db.user.findUnique({
      where: { username: session.user.username },
    });

    if (!foundUser) {
      return null;
    }

    return foundUser.votedFor;
  } catch (error) {
    console.error("Error checking vote status:", error);
    return null; 
  }
}
Yellowstripe scadOP
ahh, I see
this seems to work but it doesnt get rid of this error
@Yellowstripe scad Click to see attachment
Giant panda
you're not using "await" here
@Giant panda you're not using "await" here
Yellowstripe scadOP
im not using await there because its a client component
im probably saying some dumb shit, dont know if its right or not
Giant panda
but it (promise) needs to be resolved
@Giant panda but it (promise) needs to be resolved
Yellowstripe scadOP
what should i do then
@Yellowstripe scad Click to see attachment
Giant panda
You can make the session to be required
import { useSession } from "next-auth/react"

export default function Admin() {
  const { status } = useSession({
    required: true,
    onUnauthenticated() {
      // The user is not authenticated, handle it here.
    },
  })

  if (status === "loading") {
    return "Loading or not authenticated..."
  }

  return "User is logged in"
}

, so it will redirect to the login page if your session is either empty or unauthenticated
Yellowstripe scadOP
trying this out rn
@Yellowstripe scad Click to see attachment
Giant panda
hasVoted({ session })
    .then((voteStatus) => {
      if (voteStatus !== null) {
             what ever you wanna do

      } else {
           what ever you wanna do

    })
    .catch((error) => {
     what ever you wanna do
    });
Giant panda
https://next-auth.js.org/getting-started/client Follow this guide to learn more about handling authentication checks on the client side.
@Yellowstripe scad do I need to add the else and the catch
Giant panda
yeah that's the best way to handle error handling
@Giant panda yeah that's the best way to handle error handling
Yellowstripe scadOP
is this right?
Giant panda
see the error
@Giant panda see the error
Yellowstripe scadOP
Giant panda
just share your VoteClient component code
@Giant panda just share your VoteClient component code
Yellowstripe scadOP
the whole thing?
Giant panda
not whole just your hasVoted thing
Yellowstripe scadOP
Giant panda
i mean the previous one
Yellowstripe scadOP
this?
Giant panda
yeah
Yellowstripe scadOP
"use client"
import {CheckboxGroup} from "@nextui-org/react";
import { CustomCheckbox } from "@/components/ui/CustomCheckbox";
import YoutubeEmbed from "@/components/switches/YoutubeEmbed";
import { Button } from "@nextui-org/react";
import React, { useState } from "react";
import { useSession } from "next-auth/react";
import { Switch, Session } from "@/lib/types";
import { useRouter } from 'next/navigation'
import hasVoted from "./hasVoted"
import { toast } from "sonner";

export default function VoteClient({foundSwitch}: {foundSwitch: Switch}) {
    const router = useRouter()
    const { data: session, status } = useSession({
        required: true,
        onUnauthenticated() {
            router.push("/sign-in")
        },
    });
    const Voted = hasVoted({ session })
        .then((voteStatus) => {
            if (voteStatus !== null) {
                toast.error("You have already voted for this switch")
            } else {
                return null
            }
        })
        .catch((error) => {
            toast.error(error.message)
        });
    const [groupSelected, setGroupSelected] = useState<string[]>([]);
    const is4 = groupSelected.length < 4
    const is1 = groupSelected.length > 0
    return (
        <form className="mx-auto max-w-screen-xl flex min-h-screen mt-16 flex-col">
            <Button className='w-full mb-24' color="primary" type='submit'>
                Submit your Vote
            </Button>
            <div className="flex flex-row items-center flex-wrap">
                <p className="text-2xl">Vote for {foundSwitch.switch_name}'s Sound Descriptors</p>
                <p className="text-xs md:ml-2">(Choose 4)</p>
            </div>
            <div className="mt-2">
                <CheckboxGroup value={groupSelected} isDisabled={!is4} isRequired={true} onValueChange={setGroupSelected} name="soundDescriptors" className="flex flex-wrap gap-1" orientation="horizontal">
                    ...
                </CheckboxGroup>
                <Button color="primary" isDisabled={!is1} className="w-24 mt-4">Reset</Button>
                <p className="text-xl mt-24 pb-2">Sound Tests</p>
                <div className="grid md:grid-cols-2 lg:grid-cols-3">
                    {foundSwitch.videos.map((video_url: string, index: number) => (
                        <div className="aspect-video h-42 mr-2 mb-2" key={index}>
                            <YoutubeEmbed key={index} videoId={video_url} />
                        </div>
                    ))}
                </div>
            </div>
        </form>
    );
}
Giant panda
useState(() => {
    hasVoted({ session })
      .then((voteStatus) => {
        if (voteStatus !== null) {
          toast.error("You have already voted for this switch");
        }
      })
      .catch((error) => {
        toast.error(error.message);
      });
  }, []); //
this will trigger when your component is mounted
Yellowstripe scadOP
Giant panda
useEffect(() => {
if (session) {
hasVoted({ session })
.then((voteStatus) => {
if (voteStatus !== null) {
toast.error("You have already voted for this switch");
}
})
.catch((error) => {
toast.error(error.message);
});
}
}, [session]); this will make sure whenever your session is changed it will rerender the component
@Giant panda Click to see attachment
Yellowstripe scadOP
if I replace the toast with console.log, nothing gets logged and I get this error in the devtools console
Error checking vote status: Error: PrismaClient is unable to run in this browser environment, or has been bundled for the browser (running in `unknown`).
If this is unexpected, please open an issue: https://github.com/prisma/prisma/issues
    at Object.get (index-browser.js:199:15)
    at Module.hasVoted (hasVoted.tsx:10:36)
    at client.tsx:23:11
    at commitHookEffectListMount (react-dom.development.js:20998:23)
    at commitHookPassiveMountEffects (react-dom.development.js:23051:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23156:11)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23231:13)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23267:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23267:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23267:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23267:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23267:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23267:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23267:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23267:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
    at recursivelyTraversePassiveMountEffects (react-dom.development.js:23134:7)
    at commitPassiveMountOnFiber (react-dom.development.js:23153:9)
Giant panda
your prisma setup is incorrect imo https://github.com/prisma/prisma/issues/6219
@Giant panda your prisma setup is incorrect imo https://github.com/prisma/prisma/issues/6219
Yellowstripe scadOP
so basically I cant get if its voted without a route
like an api route
should I just use fetch instead
Giant panda
you need to setup api end points for that in order to fetch data
"should I just use fetch instead" If you've defined api routes then yes you can
@Giant panda "should I just use fetch instead" If you've defined api routes then yes you can
Yellowstripe scadOP
what would be the correct way of fetching
Giant panda
you can directly fetch data if you're using server components otherwise you need to define route handlers
@Giant panda https://codevoweb.com/how-to-setup-prisma-orm-in-nextjs-13-app-directory/
Yellowstripe scadOP
whats the difference between POST and GET
oh I see, I'd want to use post because I dont want this data to be accessible to people visiting the endpoint, right?
Giant panda
"oh I see, I'd want to use post because I dont want this data to be accessible to people visiting the endpoint, right?" yes
Yellowstripe scadOP
thank you so much for dealing with me 😂😂
Giant panda
np
:sunglasses_1: