I use the new async/await syntax, since that reads in a more intuitive way:
async fetchData(request) {
try {
const response = await fetch(request)
const data = await response.json()
// return the data if the response was ok
if (response.ok) return { data }
// otherwise return an error with the error data
const error = new Error(response.statusText)
if (data.errors) error.errors = data.errors
throw error
} catch (error) {
return { error }
}
}
It makes it very easy to handle both the promise that fetch
returns as well as the promise that response.json()
returns.