Can't properly pass error information from my NextJS API route

50 views Asked by At

created the default project using npx create-next-app@latest

src/pages/index.tsx

import useSWR from 'swr'

const fetcher = (url: string) => fetch(url).then((r) => r.json());

export default function Home() {
  const { data, error, isLoading } = useSWR('/api/hello', fetcher,{
    onSuccess: async (data) => {
      console.log('we got a success');
    },
    onError: (err) => {
      console.log('we got an error');
    }
  });
  console.log(`data: ${JSON.stringify(data)}`);
  console.log(`error: ${JSON.stringify(error)}`);
  console.log(`isLoading: ${JSON.stringify(isLoading)}`);
  return (
  <></>
  )
}

src/pages/api/hello.tsx

import type { NextApiRequest, NextApiResponse } from 'next'

type Data = {
  name: string
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  res.status(400).json({ name: 'John Doe' })
  //res.status(400).end();
}

With the code above I'm getting the log from the onSuccess method, console prints that we have data (name: 'John Doe') and error is undefined. If comment the line with json({...}) and uncomment the one with .end() I get the log from onError but I can't pass any additional information. Seems like any send method of NextApiResponse like json() or send() result in invocation of the onSuccess.

I want to be able to send JSON object in case of an error and onSuccess or onError to be called accordingly to the status passed to res.status(). What am I missing?

0

There are 0 answers