Next.JS: How to handle error in getInitialProps?
10,337
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
}
}
}
Author by
0xsh
Updated on June 28, 2022Comments
-
0xsh almost 2 years
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