Next.js Discord

Discord Forum

How to check for type returned by server action in client side?

Answered
Polish posted this in #help-forum
Open in Discord
PolishOP
This is the server action that returns either Note[] or ActionError on promise resolved

'use server'
import { getNotes } from "@/db/controller/notecontroller"
import { redirect } from "next/navigation"
import { verifySession } from "@/app/lib/dal"
import { ActionError } from "@/definations/ActionError"
export async function getOwnedNoteList() {
  let result
  try {
    const { isAuth, user } = await verifySession()
    if (isAuth && user) {
      result = await getNotes(user.user_id)
      return result as Note[]
    }
    else {
      return redirect('/login')
    }
  } catch {
    return { message: "Failed to fetch the note." } as ActionError
  }
}

And on the client side i want to do something like this
  useEffect(() => {
    const fetchNote = async () => {
      const result = await getOwnedNoteList()

      //if result is ActionError do something


      // if result is Note[] do otherthing


    }
    fetchNote()
  }


How I can do something like
if(result is ActionError)....


NEED HELP ,SUGGESTION
Answered by B33fb0n3
you can easily check if you got a notes array back by doing:
const result = await getOwnedNoteList()

if(Array.isArray(result)) {
    // only called when it is Note[]
    // if result is Note[] do otherthing
} else {
    // only called when it's an ActionError
    //if result is ActionError do something
}
View full answer

3 Replies