Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to 404 if no data from external API (universal React + Redux app)?

I have a route with params and I want to render/redirect to a 404 route if an action returns no data from an external API. What would be the most sensible way to do this?

This is the router:

    export default (
        <Route path="/" component={App}>
            <Route path=":venueName" component={Venue} />
            <Route path="*" component={NotFound} />
        </Route>
    );

The Venue component is connected to Redux and fires a action:

// ...
componentWillMount() {
    this.props.actions.fetchVenue(this.props.id);
    // want to redirect to 404 if this returns success === false
}
// ...

Action looks like this:

export const fetchVenue = (id) => ({
    type: 'FETCH_VENUE',
    payload: axios.get('http://someAddress/api/venues/id'),
});

The problem I have here is how do I figure out to do this with server-side rendering and for any amount of routes. I'm using "match" from react-router in express to render the markup. Please me know if you want me to post more code.

like image 786
Vlady Veselinov Avatar asked Feb 06 '23 22:02

Vlady Veselinov


1 Answers

The component isn't the right place for this kind of logic, IMHO. I do this in my action, and use react-router's `browserHistory. So something like:

export function fetchBrand(id) {
  return function(dispatch) {
    fetchData(`brands/${id}`, {
      headers: { 'X-Token-Auth': localStorage.getItem('token')}
    }).then(response => {
      dispatch({
        type: FETCH_BRAND_SUCCESS,
        payload: response
      });
    }).catch(err => {
       if (err.response.status == 404) {
          browserHistory.push("/my404page");
       }
    });
  }
}

And I'd have some sort of route to my404page, for example.

like image 177
Gregg Avatar answered Feb 09 '23 04:02

Gregg