React app crashes when axios fetching data response with status code 404

Viewed 480

I getting started with React App using Axios, SWR hook for fetching data, it will work fine if i received response status code success 200/OK, but my app was crashed when status code are 404, 403 or 500.

My code:

axiosConfig.js

import axios from 'axios';

const axiosConfig = axios.create({
  baseURL: 'http://localhost:5000/api',
  headers: {
    'Content-Type': 'application/json'
  },
})

axiosConfig.interceptors.request.use(request => { 
  return request;
}, function (error) {
  return Promise.reject(error)
})

axiosConfig.interceptors.response.use(response => {
  return response.data;
}, function (error) {
  return Promise.reject(error)
})

export { axiosConfig }

App.jsx

import { Suspense } from 'react'
import { Routes, Route} from 'react-router-dom'
import { SWRConfig } from 'swr'

import routes from './routes'
import Loading from './components/Loading'
import MyComponent from './components/MyComponent'

import { axiosConfig } from './axiosConfig'


const App = () => {

  return (
    <SWRConfig
      value={{
        fetcher: (url) => axiosConfig.get(url),
        dedupingInterval: 10000,
        shouldRetryOnError: false,
        revalidateOnFocus: false,
        suspense: true
      }}
    >  

      <main className="container">      
        <Suspense fallback={<Loading />}>
          <Routes>
            <Route element={<MyComponent/>} {...props} />
            // etc...
          </Routes>        
        </Suspense>
      </main>  

    </SWRConfig>  

  )
}
export default App;

MyComponent.jsx

import useSWR from "swr"

const MyComponent = () => {

    const { data, error } = useSWR('/post/1')

    if (error) return <div>Something went wrong!</div>

    return (
      // render UI
    )
}

I need handle error and show it inside MyComponent.jsx but it always crash. Who can helps me solve my problem?

0 Answers
Related