react-router: Not found (404) for dynamic content? - reactjs

How can react-router properly handle 404 pages for dynamic content in a Universal app?
Let's say I want to display a user page with a route like '/user/:userId'. I would have a config like this:
<Route path="/">
<Route path="user/:userId" component={UserPage} />
<Route path="*" component={NotFound} status={404} />
</Route>
If I request /user/valid-user-id, I get the user page.
If I request /foo, I get a proper 404.
But what if I request /user/invalid-user-id. When fetching the data for the user, I will realize that this user does not exist. So, the correct thing to do seams to be:
Display the 404 page
Return a 404 http code (for server side
rendering)
Keep the url as is (I don't want a redirect)
How do I do that?? It seams like a very standard behaviour. I'm surprised not to find any example...
Edit:
Seams like I'm not the only one to struggle with it. Something like this would help a lot: https://github.com/ReactTraining/react-router/pull/3098
As my app won't go live any time soon, I decided to wait to see what the next react-router version has to offer...

First of create a middleware function for the onEnter callback, so that this is workable for redux promises:
import { Router, Route, browserHistory, createRoutes } from "react-router";
function mixStoreToRoutes(routes) {
return routes && routes.map(route => ({
...route,
childRoutes: mixStoreToRoutes(route.childRoutes),
onEnter: route.onEnter && function (props, replaceState, cb) {
route.onEnter(store.dispatch, props, replaceState)
.then(() => {
cb(null)
})
.catch(cb)
}
}));
}
const rawRoutes = <Route path="/">
<Route path="user/:userId" component={UserPage} onEnter={userResolve.fetchUser} />
<Route path="*" component={NotFound} status={404} />
</Route>
Now in this onEnter function you can work directly with the redux store. So you could dispatch an action that either successes or fails. Example:
function fetch(options) {
return (dispatch) => {
return new Promise((resolve, reject) => {
axios.get('<backend-url>')
.then(res => {
resolve(dispatch({type: `CLIENT_GET_SUCCESS`, payload: res.data}))
})
.catch(error => {
reject(dispatch({type: `CLIENT_GET_FAILED`, payload: error}));
})
}
})
}
}
let userResolve = {
fetchUser: (dispatch, props, replace) => {
return new Promise((next, reject) => {
dispatch(fetch({
user: props.params.user
}))
.then((data) => {
next()
})
.catch((error) => {
next()
})
})
}
}
Whenever the resolve promise now fails, react-router will automatically look for the next component that it could render for this endpoint, which in this case is the 404 component.
So you then wouldn't have to use replaceWith and your URL keeps retained.

If you are not using server side rendering, returning 404 before the page gets rendered would not be possible. You will need to check for the existence of the user somewhere either way (on the server or via AJAX on the client). The first would not be possible without server side rendering.
One viable approach would be to show the 404 page on error of the Promise.

I tried my solution in a project that I am making which uses Server Side Rendering and react-router and it works there, So I'll tell you what I did.
Create a function in which you'll validate an ID. If the ID is valid, Then return the with User page with proper Component, If the ID is invalid then return the with 404 Page.
See the example:
// Routes.jsx
function ValidateID(ID) {
if(ID === GOOD_ID) {
return (
<Route path="/">
<Route path="user/:userId" component={UserPage} />
<Route path="*" component={NotFound} status={404} />
</Route>
);
} else {
return (
<Route path="/">
<Route path="user/:userId" status={404} component={Page404} />
<Route path="*" component={NotFound} status={404} />
</Route>
);
}
// Router.jsx
<Router route={ValidateID(ID)} history={browserHistory}></Router>
This should work with Server Side rendering as it did in my project. It does not uses Redux.

In case of dynamic paths, you can do it like this and you don't have to change the current path.
just import the error404 component and define a property(notfound) in the state to use for conditioning.
import React, { Component } from 'react';
import axios from 'axios';
import Error404 from './Error404';
export default class Details extends Component {
constructor(props) {
super(props)
this.state = {
project: {}, notfound: false
}
}
componentDidMount() {
this.fetchDetails()
}
fetchDetails = () => {
let component = this;
let apiurl = `/restapi/projects/${this.props.match.params.id}`;
axios.get(apiurl).then(function (response) {
component.setState({ project: response.data })
}).catch(function (error) {
component.setState({ notfound: true })
})
}
render() {
let project = this.state.project;
return (
this.state.notfound ? <Error404 /> : (
<div>
{project.title}
</div>
)
)
}
}

I encountered a similar problem while making a blog website. I've been searching for a solution for a while now. I was mapping (using map function) my blog component based on dynamic link.
The initial code snippet was as follows:
import Blog from '../../Components/Blog/Blog.component';
import './BlogPage.styles.scss';
const BlogPage = ({ BlogData, match }) => {
return (
<div className='blog-page'>
{
BlogData.map((item, idx)=>
item.link === match.params.postId?
<Blog
key={idx}
title={item.title}
date={item.date}
image={item.image}
content={item.content}
match={match}
/>
:''
)
}
</div>
)
};
export default BlogPage;
I used a hack where I would use filter function instead of map and store it and then check if it exists (in this case check if length greater than zero for result) and if it does the blog component is rendered with the props for the page else I render the Not Found component (My404Component).
The snippet as follows:
import Blog from '../../Components/Blog/Blog.component';
import My404Component from '../../Components/My404C0mponent/My404Component.component';
import './BlogPage.styles.scss';
const BlogPage = ({ BlogData, match }) => {
const result = BlogData.filter(item => item.link === match.params.postId);
console.log(result);
return (
<div className={result.length>0? 'blog-page': ''}>
{
result.length>0?
<Blog
title={result[0].title}
date={result[0].date}
image={result[0].image}
content={result[0].content}
match={match}
/>
:<My404Component />
}
</div>
)
};
export default BlogPage;
This way the Blog component is not rendered as long as the value of the entered link is not valid as result would be an empty array and it's length would be 0 and instead My404Component would be rendered.
The code is a little raw I havn't refactored it yet.
Hope this helps.

Related

How to use "<Redirect>" inside a function?

This is my function so that when a user logs in, it checks the user's password and username and if they are both correct it should redirect to the /note url with the user ID passed through it. I have seen people use it on render(), but I would like to keep my App.jsx app simple, I think that's good practice.
I have tried using the useHistory method, but when the user inputs a data, the user needs to refresh the page manually for the new data to show. If I add a useHistory to refresh the page, it says that the location.state value is undefined.
How should I go about this problem?
Thank you
// Checking to see if current user's log info exists in db
function logIn(e) {
e.preventDefault();
const currentUser = users.find(
(users) => users.username === userInput.username
);
if (!currentUser) {
console.log("The Username was not found. Please try again");
} else {
if (currentUser.password === userInput.password) {
// history.push("./note", { userId: currentUser._id });
return <Redirect to={"/note/" + currentUser._id} />;
} else {
console.log("The password is incorrect");
}
}
}
Here's my routing code
import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import NoteDashboard from "./NoteDashboard";
import Home from "./Home";
import CreateAccount from "./CreateAccount";
function App() {
return (
<Router>
<div className="container">
<Switch>
<Route exact path="/" component={Home}></Route>
<Route path="/create" component={CreateAccount}></Route>
<Route path="/note" component={NoteDashboard}></Route>
</Switch>
</div>
</Router>
);
}
export default App;
The only thing (I found) you can do to redirect to a page from function is use ReactDOM.hydrate. Here an example. Example works, but only first time. After that, redirection stops to works. Maybe because codesandbox concats to url the symbol # for some technical reason that I don't know. Try to apply this solution locally an let me know if works more tha one time.
Okay I got it to work, but I don't know if this is good practice or not.
Inside the if statement where I check to see that it is the correct user, I call a function which changes a React Hook from false to true, then in my return statement, I say
{redirect ? <Redirect to={"/note/" + currentUserId} /> : null}
It seems to work fine, everything works. Does this look like a good solution or are there some flaws that I am not seeing.
Thank you for all the help.
try something like this:
state = {
username: '',
app_pass: '',
redirectLink: '',
redirect: false
};
componentDidMount() {
if (window.localStorage.getItem('access_token')) {
this.setState({ redirectLink: '/user/dashboard', redirect: true });
}
}
render() {
const { redirect } = this.state;
const { redirectLink } = this.state;
if (redirect) {
return <Redirect to={redirectLink} />;
}
}

ReactJS ensure only owner of object can edit/delete

I do RBAC and authorization on the backend part of the application (NodeJS) and never really bothered about enforcing authorization on the UI as well.
However, let's say I have the following React Router 4 routes:
<Switch>
<Route exact path="/books/all" component={BookList} />
<Route exact path="/books/new" component={BookNew} />
<Route exact path="/books/:bookId" component={BookDetails} />
<Route exact path="/books/:bookId/edit" component={BookEdit} />
</Switch>
And I want to make sure that if a logged in user visits a book that is not his, he is not able to render the route /books/<not my book>/edit. I am able to do this by implementing a simple check at the ComponentDidMount() function:
checkAuthorisation = userId => {
if (this.props.authenticated._id !== userId) {
this.props.history.push("/books/all");
}
};
But I was wondering whether there is a better approach / design pattern of doing it in ReactJS? I was wondering whether removing the bookId altogether from the route and just push props like edit and bookId:
<Route exact path="/books/edit" component={BookEdit} />
I would recommend to do a conditionnal render in your BookEdit component (especially if you need to do an async operation to determine authorization).
I would not use a private route here in order to keep the role/auth based routing simple.
In your edit component : check authorization, if false handle this as an error and render an error component (error message and back button, can also be your 404 view), else render your edit component.
To be consistent, you must also make sure you do not have links to this error (conditionnal disabled "Edit" button on the book view if not authorized).
Example (using async check, may not be your case here but this is a general idea) :
class EditComponent extends React.Component {
state = {
loading: true,
error: null,
bookProps: null,
};
componentDidMount() {
const { match, userId } = this.props;
getBook(match.params.bookId) // request book props
.then(book => {
if (book.ownerId !== userId) { // authorization check
this.setState({ error: 'Unauthorized', loading: false });
} else {
this.setState({ bookProps: book, loading: false });
}
})
.catch(err => {
this.setState({ error: err.message, loading: false });
});
}
render() {
const { loading, error, bookProps } = this.state;
if (loading) {
return <LoadingSpinner />;
}
if (error) {
return <ErrorComponent message={error} />;
}
return <BookEditComponent book={bookProps} />;
}
}

React/Redux/Router - Auth0 login on load

I am creating a new React single page application and am trying to integrate with Auth0. I have been working with the React example but can't seem to get it working properly so that you are required to login immediately after the app loads. The problem I have now is that you are redirected to the login page twice because the app is rendering before the authentication is finished the first time. These are the important chunks of code:
index.js:
function initAuth(callback) {
const auth = store.getState().app.auth;
if(!auth.isAuthenticated()) {
auth.login();
}
callback();
}
//Authorize the app and then render it
initAuth(function () {
render(
<Provider store={store}>
<ConnectedRouter history={history}>
<div>
<App />
</div>
</ConnectedRouter>
</Provider>,
target
);
});
app.js:
const App = props => (
<div>
//... Other stuff
<Routes/>
//... More stuff
</div>
);
routes.js:
const Routes = props => (
<main>
<Switch>
//...Other Routes Are Here
<Route path="/callback" render={(props) => {
return <Callback data={props} {...props} />;
}}/>
<Redirect from='*' to='/'/> {/*Any unknown URL will go here*/}
</Switch>
</main>
);
callback.js:
const auth = store.getState().app.auth;
const handleAuthentication = (nextState) => {
console.log('Evaluation: ', /access_token|id_token|error/.test(nextState.location.hash))
if (/access_token|id_token|error/.test(nextState.location.hash)) {
auth.handleAuthentication();
}
};
class Callback extends Component {
componentDidMount() {
handleAuthentication(this.props.data);
}
//... Render method etc
}
auth.js:
login() {
this.auth0.authorize();
}
handleAuthentication() {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
history.replace('/home');
} else if (err) {
history.replace('/home');
alert(`Error: ${err.error}. Check the console for further details.`);
}
});
}
isAuthenticated() {
// Check whether the current time is past the
// access token's expiry time
let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
return new Date().getTime() < expiresAt;
}
Right now my app basically works. The only issue is that you are required to login twice because there is a race condition between the login response and the app load/check. Why it is happening makes perfect sense but I am not sure how best to fix it.
I keep a flag on state indicating that the application is booting. This flag is true until a few checks have been made including verifying if the user is already authenticated.
This prevents rendering of any components and just shows a loading indicator. Once the booting flag has been set to false the router will render.

How to reload a component in reacts on url parameter change?

I have the following route:-
ReactDOM.render((
<Router history={browserHistory}>
<Route path="/" component={app}>
<IndexRoute component={home}/>
<Route path="/articles" component={articles} />
<Route path="/articles/topics/:featureName" component={filteredArticles} />
</Route>
</Router>
), document.getElementById('app'));
Now when i request for /articles/topics/topic1, the first 5 contents are fetched are using API call. When user reaches the bottom of the page again an API call is made where next 5 contents are fetched. This is working fine(Notice that the handlescroll function checks for the page bottom, which has few minor issues so commented that out for now.)
Now say I choose next topic from the list so the url changes, so my url changes to /articles/topics/topic2 , now i need the same thing as mentioned above and call apis for this topic.
Following is my current component code:-
import React from 'react';
import axios from 'axios';
import ArticleList from './ArticleList';
import Banner from './Banner';
import LeftNavBar from './LeftNavBar';
import RightNavbar from './RightNavbar';
import {url} from './Constants';
/*MERGE INTO ARTICLES ONCE SCROLL LOGIC IS FIXED*/
class FilteredArticles extends React.Component{
constructor(){
super();
{/* Adding global event listener,binding it to scroll event and adding it to handleScroll function */}
/*window.addEventListener("scroll", this._handleScroll.bind(this));*/
this.state ={
articles : [],
loadingFlag:false,
limit : 5,
offset :0,
subFeatureName:[],
flag: false
}
}
_getContent(){
let self=this;
axios.get(url+'/articles/filter/?filter=popular&category='+this.props.params.featureName+'&limit='+this.state.limit+'&offset='+this.state.offset)
.then(function(response){
/*Checking if limit has exceeded meta count, if it has stopped we dont call the APIS*/
if(self.state.limit >= response.data.meta.total_count){
self.setState({articles : self.state.articles.concat(response.data.results),
offset : self.state.limit,
limit: self.state.limit+self.state.offset,
subFeatureName: self.props.params.featureName,
loadingFlag: false}
)
}
else{
self.setState({articles : self.state.articles.concat(response.data.results),
offset : self.state.limit,
limit: self.state.limit+self.state.offset,
subFeatureName: self.props.params.featureName,
loadingFlag: true}
)
}
})
.catch(function(error){
console.log(error);
});
}
_handleScroll(){
/*Calling 5 more articles when someone scrolls down and reaches the page end
const windowHeight = window.innerHeight;
const scrollT = $(window).scrollTop();
if(windowHeight- scrollT < 200){
if(!this.state.loadingFlag){
this.setState({loadingFlag : true});
this._getContent();
}
}*/
}
componentDidMount(){
/*calling _getContent function to get first five articles on page load*/
console.log("got content");
this._getContent();
}
render(){
console.log("inside render");
return(
<div>
<Banner title="Article Page"/>
<div className="content-container">
<LeftNavBar/>
<div className ="feeds">
<div className="card">
{/* Sending hideSeeAll as prop to remove see all button on main article page*/}
<ArticleList articles={this.state.articles} hideSeeAll='true' keyword="Top Articles"/>
</div>
</div>
<RightNavbar/>
</div>
</div>
)
}
}
export default FilteredArticles;
So basically I am trying to understand that if I have a route like /articles/topics/:featureName and I call a page like /articles/topics/topic1 or /articles/topics/topic2, can the component be realoaded(I need to call different API are fetch content once again).
That is, for /articles/topics/topic1 the API called is
/api/v0/articles/filter/?filter=popular&category=topic1&limit=5&offset=0
and for /articles/topics/topic2 the API called is
/api/v0/articles/filter/?filter=popular&category=topic2&limit=5&offset=0
Is there any way to achieve this?
You shouldn't really be querying the API/updating the components state in this fashion but hey that's another question entirely. Maybe consider using a Flux approach.
Anyhow, you can use the componentWillReceiveProps(nextProps) life cycle method to receive the routers nextProps params and query your API again:
componentWillReceiveProps(nextProps) {
this._getContent(nextProps.params.featureName);
}
_getContent(featureName) {
...query your API
}
Also, if you're using Redux, make a check like this to avoid an infinite loop:
componentWillReceiveProps(newProps) {
if (this.props.someValue === newProps.someValue) {
this.props.fetchSomething(newProps.params.somethingName);
}
}

Get the current route name into the component

I am trying not to use : if(window.location) to get access to my current route.
I am working on a code where the router is already defined, and the component is already written. I am trying to access the router information from the component because I need to apply a classname depending on the route.
Here's how the router looks like:
export const createRoutes = (dispatch, getState) => (
<Route component={AppLayout} >
<Route path="/" component={Home} onEnter={(nextState, replaceState) => {
console.log('on Enter / = ', nextState);
nextState.test = 'aaaa'; //can't seem to pass states here....
}} />
then in my component:
render() {
//I want to access my super router or location . in fact
// I just want to know if currentURl === '/'
//and after reading the react-router doc 5 times - my head hurts
// but I still hope to get an answer here before putting a window.location
}
`
Depending on which version of React Router you're using you have access to different objects available on the context of a component.
MyComponent.contextTypes = {
location: React.PropTypes.object
}
which will enable you to do the following
render() {
if (this.context.location.pathname === '/') {
return <h1>Index</h1>;
} else {
return <h2>Not index</h2>;
}
}

Resources