frontarm / navi

🧭 Declarative, asynchronous routing for React.
https://frontarm.com/navi/
MIT License
2.07k stars 71 forks source link

Question: Prevent routing on async route data fetch error #156

Closed Menci closed 4 years ago

Menci commented 4 years ago

Let's see the example in the document. Async data fetch can fail. What to do if I want to prevent routing on the error?

import React from 'react'
import { mount, redirect, route } from 'navi'
import { QuoteView, fetchQuote } from './helpers'

const routes = mount({
  '/': redirect('/quotes/1'),

  // The ':id' segment will match any value, and its value is made
  // available within the route at `req.params.id`.
  '/quotes/:id': route(async req => {
    let id = req.params.id
    let [failed, quote] = await fetchQuote(id) // This can fail

    if (failed) {
        // Show an error message
        // Tell navi do not route
    }

    return {
      view: <QuoteView id={id} quote={quote} />,
    }
  })
})

export default routes
jamesknelson commented 4 years ago

To handle this, you can use a map() instead of a route(). Then, you can return a different route or redirect depending on whether the request succeeds or fails.

Menci commented 4 years ago

Awesome!