fetch as a try catch code example
Example 1: try catch fetch
fetch("/api/foo")
.then( response => {
if (!response.ok) { throw response }
return response.json()
})
.then( json => {
this.props.dispatch(doSomethingWithResult(json))
})
.catch( err => {
err.text().then( errorMessage => {
this.props.dispatch(displayTheError(errorMessage))
})
})
Example 2: fetch error handling js
export async function getStaticProps(context) {
const res = await fetch(`https://...`)
const data = await res.json()
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: {},
}
}