react-router-dispatcher-status-code
v2.0.0
Published
react-router-dispatcher action to assign HTTP status codes
Downloads
23
Maintainers
Readme
react-router-dispatcher-status-code
A react-router-dispatcher action for defining react-router status codes that support server-side streaming.
Read the react-router-dispatcher documentation if you haven't already done so.
Install
NPM
npm install --save react-router-dispatcher-status-code
Yarn
yarn add react-router-dispatcher-status-code
Usage
import statusCodeAction, { withStatusCode, STATUS_CODE } from 'react-router-dispatcher-status-code';
// STATUS_CODE is the action name, used to configure react-router-dispatcher
Example
Defining routes using withStatusCode()
// routes.js
import { withStatusCode } from 'react-router-dispatcher-status-code';
import { Root } from './components';
const routes = [
{ component: Root,
routes: [
{ path: '/',
exact: true,
component: Home
},
// Configure a 404 - not found route for rendering invalid routes
{ component: withStatusCode(404)(NoMatch) }
]
}
]
export default routes;
Configuring the metadata action using react-router-dispatcher
import { createRouteDispatchers } from 'react-router-dispatcher';
import { STATUS_CODE } from 'react-router-dispatcher-status-code';
import routes from './routes';
const {
UniversalRouteDispatcher,
ClientRouteDispatcher,
dispatchClientActions,
dispatchServerActions
} = createRouteDispatchers(routes, [[STATUS_CODE]]);
// Server dispatch
dispatchServerActions(req.url, params).then(({ httpResponse: { statusCode } }) => {
if (statusCode >= 300 || statusCode < 400) {
// redirect - expressjs syntax
return res.redirect(statusCode, ....);
}
// Set the HTTP response code - expressjs syntax
res.status(statusCode);
if (statusCode >= 500) {
// render an error page
}
// render the app
});
API
statusCodeAction(statusCode)
Parameters
statusCode: number
- The statusCode to assign to the response
withStatusCode(statusCode)
Parameters
statusCode: number
- The statusCode to assign to the response
Contribute
For questions or issues, please open an issue, and you're welcome to submit a PR for bug fixes and feature requests.
Before submitting a PR, ensure you run npm test
to verify that your coe adheres to the configured lint rules and passes all tests. Be sure to include unit tests for any code changes or additions.
License
MIT