I'm working on a website using server-side rendering approach. I'm using React and Redux for this. Redux handles the state of the application and provides API to change the state. All asynchronous data fetching is done via Redux.
The problem is that a URL may be like example.com/news/:param
where param
is some dynamic parameter like a country for example. In React I have a page which is common to all news
pages so because the URL path starts with news
react-router will find a page for it. However, if a user enters a non-valid country 404 page should be returned. Whether a country or any other param
is valid can only be determined via a request to the API service I'm using, that is using Redux actions.
Another complication is that a given page may need to make several requests to the API in order to fetch data. If param
is found in the API but some other less important data is not found I don't want to display 404 page. 404 page should therefore displayed only if the "main" request to the API returns 404.
Current solution:
So far in "main" requests to the API, I tentatively switch on notFound
variable. That is I suspect that a request which contains an param
potentially may result in 404 because the param
was not found. So if such request indeed results in 404 status then my main component in React detects that notFound
is now true and shows the default Not Found page to the user.
In addition I have a variable in Redux state which is called internalError
. It is set to true if some internal error occurred, often as a result of a request to API, e.g. JSON parsing error, etc. internalError
is always the opposite boolean value of notFound
. This way when we are in the main reducer which calculates the new values for internalError
and notFound
then if notFound
is false then error
will be true and this way we know that we need to display 500 error to the user instead of 404.
This approach has several issues:
- Race condition between Redux actions which set
notFound
to true and Redux actions that setnotFound
back to false. - Imagine a situation when 500 error may occur due to some unimportant Promise rejection (thus setting
internalError
to true) but later another API request will return 404 for the requestedparam
. So first the user will see a generic error page with 500 status then a Not Found page. It's another race condition.
I'm wondering if there's a simpler, better approach.