简体   繁体   中英

Next.JS: How to handle error in getInitialProps?

I want to fetch data from an API, and if it fails I want it to render the _error.js page. My request depends on the router query. So if the user enters a wrong query the page is going to throw an error.

If the request fails by throwing, I want my custom _error.js to be displayed.

How do I achieve this?

Here is my index page:

// pages/index.js

import React from 'react'
import PropTypes from 'prop-types'
import fetch from 'isomorphic-unfetch'
import Items from '../components/Items'
import { API } from '../utils/config'

const IndexPage = ({ items }) => {
  return (
    <div>
      <Items items={items} />
    </div>
  )
}

IndexPage.getInitialProps = async (context) => {
  const { query } = context
  const filter = query.filter || ''
  const name = query.name || ''
  const page = query.page || 1
  const response = await fetch(
    `${API}?${filter}=${name}&page=${page}`,
  )
  const data = await response.json()
  return {
    items: data.items,
  }
}

export default IndexPage

my _app file:

// pages/_app.js

import React from 'react'
import Router from 'next/router'
import Page from '../components/Page'

const MyApp = (props) => {
  const { Component, pageProps } = props
  return (
    <Page>
      <Component
        items={pageProps.items}
        query={pageProps.query}
        statusCode={pageProps.statusCode}
      />
    </Page>
  )
}

export default MyApp

Try Conditional rendering based on the error, so if in an error occurs set the items to null

  const IndexPage = ({ items }) => {

      return (
      {items===null ? <Fragment>
         <ErrorPage />
     </Fragment> : <div>
          <Items items={items} />
        </div> } 
      )
    }

and in the getInitialProps

IndexPage.getInitialProps = async (context) => {
  try{
  const { query } = context
  const filter = query.filter || ''
  const name = query.name || ''
  const page = query.page || 1
  const response = await fetch(
    `${API}?${filter}=${name}&page=${page}`,
  )
  const data = await response.json()
  return {
    items: data.items,
  }
 }catch(error){
    return {
    items: null
  } 
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM