Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get the response error from useSWR error property

I am using Next.js, and trying a little testing of SWR before integrating it into my app. So this below is just a faker.api test to see how it goes and get familiar with it.

Everything is working pretty well, but for some reason I can't seem to be able to get the error back, my console log does not print anything in the console.

import type { NextPage } from 'next'
import { useState } from 'react'
import useSWR, { SWRConfig } from 'swr'
import UseBooks from '../Hooks/UseBooks'

type HomeProps = NextPage & {
  serverData: any
}

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

const Home = ({serverData}: HomeProps) => {
const [shouldFetch, setShouldFetch] = useState(false)
const {data, error} = useSWR(
  `https://fakerapi.it/api/v1/ompanies?_quantity=10`,
  fetcher,
  {
    fallbackData: serverData,
    onError: (error, key)=> {
     console.log(error)
    }
  })

const  [booksData, booksError]  = UseBooks(shouldFetch, 'https://fakerapi.it/api/v1/books?_quantity=10')
const handleClick = () => {
  setShouldFetch(true)
}

  return (
    <div>
        {JSON.stringify(booksData)}
        <ul>
          {data?.data?.map(el => (
            <li key={el.id}>{el.name}</li>
          ))}
        </ul>
        <button onClick={handleClick}>next</button>
    </div>
  )
}

export async function getServerSideProps(){
  const res = await fetch(`https://fakerapi.it/api/v1/companies?_quantity=10`)
  const serverData= await res.json()
  return{ props:{serverData}}
}

export default Home
like image 860
julBayonna Avatar asked Oct 26 '25 10:10

julBayonna


1 Answers

This is expected behaviour because fetch doesn't actually reject when the request returns a non-2xx response, it only does so when a network error occurs. If you log data to the console, you'll notice that it contains the error response body: { status: "Not found", code: 404, total: 0 }.

You can use the fetch response's ok property to determine whether the request returned a 2xx response, and if not throw an error yourself.

const fetcher = (url: string) => fetch(url).then(r => {
    if (!r.ok) {
        throw new Error('Something went wrong with the request')
    }
    return r.json()
}) 

Alternatively, you can use axios instead - as it will throw an error when a non-2xx response is returned.

const fetcher = (url: string) => axios(url).then((r) => r.data);
like image 58
juliomalves Avatar answered Oct 28 '25 03:10

juliomalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!