I have this privateRoute component that I use to manage authentication:
const PrivateRoute = ({ component: Component, auth, ...rest }) => {
// This gets logged twice when I navigate in the app
// Using history.push("/url")
// And gets logged once when I type the url and hit enter on the browser
console.log(
"===============INSIDE PrivateRoute Component========================"
);
return (
<Route
{...rest}
render={(props) =>
auth.isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
};
The strange thing is that this component gets logged twice when I navigate in the app. For example, when I hit a button that triggers this code:
this.props.history.push("/edit-page-after-login");
And I have this in App.js:
<PrivateRoute
path="/edit-page-after-login"
component={EditProfileAfterLogin}
/>
And I have a component that gets rendered in that route:
export default class EditProfileInSettings extends Component {
componentDidMount() {
console.log(
"π ~ file: EditProfileInSettings.js ~ line 5 ~ EditProfileInSettings ~ componentDidMount ~ componentDidMount"
);
}
render() {
return <div>Test</div>;
}
}
So when I navigate to that component using history.push, this gets logged:
===============INSIDE PrivateRoute Component========================
π ~ file: EditProfileInSettings.js ~ line 5 ~ EditProfileInSettings ~
componentDidMount ~ componentDidMount
===============INSIDE PrivateRoute Component========================
For some strange reason, PrivateRoute component gets called TWICE which is causing me some issues in the logic I am trying to implement.
But, when I write the url in the browser and enter, it behaves correctly and it only gets called ONCE:
===============INSIDE PrivateRoute Component========================
π ~ file: EditProfileInSettings.js ~ line 5 ~ EditProfileInSettings ~
componentDidMount ~ componentDidMount
Any idea what's going on here?
EDIT 1: I have noticed this error only occurs when I do an API call to the backend inside the component:
class PrivateRouteTestComponent extends Component {
componentDidMount() {
console.log("PrivateRouteTestComponent.componentDidMount is called!");
// If I comment this out, the problem will not occur.
// It only occurs with this line
// It does an API call to the backend to get user profile
this.props.getAuthenticatedUserProfile();
}
render() {
return (
<div>
<button
onClick={() => {
this.props.history.push("/videos-page");
}}
>
Home
</button>
<h6>Private route test component</h6>
</div>
);
}
}
EDIT 2: I finally found why this error occurs. Calling a function that dispatches something to the store will update the PrivateRoute so it will get called again:
class PrivateRouteTestComponent extends Component {
componentDidMount() {
console.log("PrivateRouteTestComponent.componentDidMount is called!");
// This doesn't cause the problem
testBackendCall();
// This causes the problem
// Because it dispatches an action to the store
// So PrivateRoute gets updated
this.props.testBackendCallThatDispatchesSomethingToTheStore();
}
render() {
return (
<div>
<button
onClick={() => {
this.props.history.push("/videos-page");
}}
>
Home
</button>
<h6>Private route test component</h6>
</div>
);
}
}
You're mixing functional components and React class-based components, and expect that the logging in PrivateRoute and the one in EditProfileInSettings to be done at the same moment in the rendering cycle - but it's not.
In EditProfileInSettings, you log on the mounting phase (componentDidMount), which happens once in a component's rendering (if not unmounted).
In PrivateRoute, you log on the rendering phase (think the equivalent of render on a class Component), which happens every time React needs to update your component because of its props being changed.
If you want the two logging to be equivalent, either place your logging in a useEffect() on your PrivateRoute, or place your logging at the render() on your EditProfileInSettings.
Then, to know why your functional component is rendered two times, log all your props and spot the differences between two cycles.
This is what solved my problem. Using React hooks to execute code in functional component only when it's mounted.
const PrivateRoute = ({ component: Component, auth, ...rest }) => {
React.useEffect(() => {
// EXECUTE THE CODE ONLY ONCE WHEN COMPONENT IS MOUNTED
}, []);
return (
<Route
{...rest}
render={(props) =>
auth.isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
};
Related
I use the useEffect hook to dispatch the getQuestions function in order to get the data from the server
function App () {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getQuestions());
}, [dispatch]);
return (
<Routes>
<Route exact path="/" element={<Layout/>}>
<Route path="repetition" element={<Repetition/>}/>
<Route path="family" element={<Family/>}/>
</Route>
</Routes>
);
}
The problem is that when I, for example, open the family link (which I declared in the App function), initially I get the data, but when I refresh the page, the data disappears.
I certainly understand that when the page is refreshed the parent App component is not rendered from this and I get an error, similar issues I have looked at in the forums where it was suggested to use withRouter which updates the parent component, but my version of react-router-dom does not supports withRouter, except that I don't want to downgrade my version of react-router-dom to use withRouter.
I would like to know if there is any way to fix this problem.
I tried the option that #Fallen suggested, i.e. I applied the useEffect hook in each child element and analyzed this approach in GoogleLighthouse, and I'm happy with the results.
Here is my final code in child component
function Family () {
const dispatch = useDispatch();
const questions = useSelector(state => state.QuestionsSlices.familyQuestions);
useEffect(() => {
dispatch(getFamilyQuestions());
}, [dispatch]);
return (
<>
{questions.data.map((item, idx) => (
<div key={idx}>
{ idx + 1 === questions.score && CheckQuestionsType(item, questions) }
</div>
))}
</>
);
}
I have following App component:
<Route render={( { location } ) => (
<TransitionGroup component="div" className="content">
<CSSTransition key={location.key} classNames="slide" timeout={{
enter: 1000,
exit: 300
}} appear>
<Switch location={location}>
<Route exact path='/' component={Intro}/>
<Route path="/history" component={History}/>
<Route path="/rules" component={Rules}/>
<Route path="/faq" component={Faq}/>
<Route path="/feedback" component={Feedback}/>
<Route path="/partners" component={Partners}/>
</Switch>
</CSSTransition>
</TransitionGroup>
)}/>
And it works fine, but every animation executes immediately. For example, if I go from /rules to /history, I got full animation on both components, but history component require data from the server, so animation applied on empty container.
How could I pause animation in react-transition-group components? I have Redux, so I could change loading variable anywhere in my app. Also, I don't want to preload all data in the store on app start.
I would make your component return null when it's loading and make the loading state determine the CSSTransition key like <CSSTransition key={location.key+loading?'-loading':''}
see example here: https://stackblitz.com/edit/react-anim-route-once
note that to make this work without duplication I had to make the component copy the loading prop and persist it in state, so that one of the copies of the component never displays (which would create a duplication of the component as seen here: https://stackblitz.com/edit/react-anim-route-twice)
<Route render={({ location }) => (
<TransitionGroup component="div" className="content">
<CSSTransition key={location.key+(this.state.loading?'-loading':'-loaded')} classNames="crossFade" timeout={{
enter: 3000,
exit: 3000
}} appear>
<Switch location={location} >
<Route exact path='/' component={Hello} />
<Route exact path='/history' render={() =>
<Delayed setLoading={this.handleSetLoading} loading={this.state.loading} />} />
</Switch>
</CSSTransition>
</TransitionGroup>
)} />
and in the component something like this:
export default class History extends React.Component {
state={loading:this.props.loading}
componentDidMount() {
setTimeout(() => {
this.props.setLoading(false);
}, 2000);
}
render() {
return !this.state.loading ? <div><h1>History! <Link to="/">Home</Link></h1></div> : null;
}
}
So my cases have been a bit different but they might help you think of a solution.
You can delay the initial display easily by adding an if (this.state.isloaded == true) block around your whole router. Start loading when your component mounts, and when the async call completes, setState({isloaded: true}).
You can make your own <Link> component, which launches a request, and only once itβs complete changes the page location. You can do whatever special loading spinners you like in the meantime.
Basically, keep the routing and transition components to one side. I find them to be brittle and painful with cases like this. Let me know if you want any more details or snippets.
I've done peloading through redux and redux-saga. Maybe it's one and only way to achieve following with react-router and react-transition-group, because transition toggle animation anytime when render method is run, even if it return null.
I've implemented following actions:
const LoadingActions = {
START_LOADING: 'START_LOADING',
STOP_LOADING: 'STOP_LOADING',
REDIRECT: 'REDIRECT',
startLoading: () => ({
type: LoadingActions.START_LOADING
}),
stopLoading: () => ({
type: LoadingActions.STOP_LOADING
}),
redirect: ( url, token ) => ({
type: LoadingActions.REDIRECT,
payload: {
url,
token
}
})
};
export default LoadingActions;
In the reducers I've implemented simple loader reducer, that will toggle on and off loading variable:
import { LoadingActions } from "../actions";
const INITIAL_STATE = {
loading: false
};
export default function ( state = INITIAL_STATE, { type } ) {
switch ( type ) {
case LoadingActions.START_LOADING:
return { loading: true };
case LoadingActions.STOP_LOADING:
return { loading: false };
default:
return state;
}
}
The most irritating thing is reducer chain - this.props.loader.loading. Too complex for such simple thing.
import { combineReducers } from "redux";
...
import LoadingReducer from './LoadingReducer';
export default combineReducers( {
...
loader: LoadingReducer
} );
This most work goes in saga:
function* redirect ( action ) {
yield put( LoadingActions.startLoading() );
const { url } = action.payload;
switch ( url ) {
case MENU_URL.EXCHANGE:
yield call( getExchangeData, action );
break;
... other urls...
}
yield put( LoadingActions.stopLoading() );
BrowserHistory.push( url );
}
... loaders ...
function* watchRedirect () {
yield takeLatest( LoadingActions.REDIRECT, redirect );
}
const sagas = all( [
...
fork( watchRedirect )
] );
export default sagas;
I put listener on redirect action, so it will call redirect generator. It will start loading and call data preloading yield call will await for preload to finish and after it will stop loading and redirect. Though it won't wait for positive result, so preloaders should handle errors themselves.
I hoped that I could avoid redux complexity with built-in feature of router or transition library, but it has no such tools to stop transition. So it is one of the best way to achieve transition with preloded data.
I'm coding an authentication with react-router v4 and I'm using the PrivateRoute with render props, like the documentation: Redirects (Auth)
What I'm trying to do is: Whenever the user navigates to a route, I want to dispatch an action to make a request to the backend to verify if he's logged in.
Like this:
// App.js
class App extends Component {
checkAuth = () => {
const { dispatch, } = this.props;
// callback to dispatch
}
render() {
const props = this.props;
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/" component={Login} />
<PrivateRoute
exact
path="/dashboard"
component={Dashboard}
checkIsLoggedIn={this.checkAuth}
/>
{/* ... other private routes here */}
</Switch>
</div>
</Router>
);
}
In PrivateRoute.js I'm listening the route to check if it changes, but when a route changes, this function is called too many times, and that's a problem to dispatch an action to make a request.
// PrivateRoute.js
const PrivateRoute = ({ component: Component, auth, checkIsLoggedIn, ...rest }) => (
<Route
{...rest}
render={props => {
props.history.listen((location, action) => {
if (checkIsLoggedIn) {
// Here I check if the route changed, but it render too many times to make a request
checkIsLoggedIn(); // here is the callback props
}
});
if (auth.login.isLoggedIn) {
return <Component {...props} />;
} else {
return <Redirect to={{ pathname: "/login", state: { from: props.location } }} />
}
}
}
/>
);
I need a help to figure it out a good way to call the backend whenever the route changes.
Creating a Higher Order Component (HOC) is a very clean way to do this. This way, you won't need to create a separate PrivateRoute component, and it would take only one line of change to convert any Component from public to protected, or vice versa.
Something like this should work:
import React from 'react';
import { Redirect } from "react-router-dom";
export function withAuth(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
isUserLoggedIn: false,
isLoading: true
};
}
componentDidMount() {
// Check for authentication when the component is mounted
this.checkAuthentication();
}
checkAuthentication() {
// Put some logic here to check authentication
// You can make a server call if you wish,
// but it will be faster if you read the logged-in state
// from cookies or something.
// Making a server call before every protected component,
// will be very expensive, and will be a poor user experience.
this.setState({
isUserLoggedIn: true, // Set to true or false depending upon the result of your auth check logic
isLoading: false
});
}
render() {
// Optionally, you can add logic here to show a common loading animation,
// or anything really, while the component checks for auth status.
// You can also return null, if you don't want any special handling here.
if (this.state.isLoading) return (<LoadingAnimation />);
// This part will load your component if user is logged in,
// else it will redirect to the login route
if (this.state.isUserLoggedIn) {
return <WrappedComponent authData={this.state} {...this.props} />;
} else {
return <Redirect to={{ pathname: "/login", state: { from: props.location } }} />;
}
}
}
}
Once you have that component in place, all you need to do is use the HOC in any component that you wish to have protected. For example, in your case, the export line in your Dashboard file would be something like this:
/* Dashboard.js */
class Dashboard extends React.Component { ... }
export default withAuth(Dashboard);
and in your App, you can use a simple Route component:
<Route exact path='/dashboard' component={Dashboard} />
Your App does not need to care about which routes are protected, and which ones aren't. In fact, only the actual components need to know that they are protected.
Hope this helps. Cheers! :)
I have the next code:
import React from 'react'
import Loadable from 'react-loadable'
import { Route } from 'react-router-dom'
class App extends React.Component {
state = {
kappa: false
}
componentDidMount() {
setTimeout(() => {
setState({ kappa: true })
}, 1000)
}
render() {
return (
<div className="app">
<Route exact path="/:locale/" component={Loadable({
loader: () => import('../views/IndexPage/index.jsx'),
loading: () => "loading"
})} />
<Route exact path="/:locale/registration" component={Loadable({
loader: () => import('../views/Registration/index.jsx'),
loading: () => "loading"
})} />
{this.state.kappa && <p>Hey, Kappa-Kappa, hey, Kappa-Kappa, hey!</p>}
</div>
)
}
}
When state updates (kappa becomes true and p appears), component on active route (no matter what is it - IndexPage or Registration) remounts. If I import component manually in App and pass it to the Route without code-splitting, components on routes doesn't remount (that's so obvious).
I also tried webpack's dynamic import, like this:
<Route path="/some-path" component={props => <AsyncView {...props} component="ComponentFolderName" />
where import(`/path/to/${this.props.component}/index.jsx`) runs in componentDidMount and upfills AsyncView's state, and it behaves simillar to Loadable situation.
I suppose, the problem is that component for Route is an anonymous function
The question is: how to avoid remount of route components?
Well, this behaviour is normal and documented at React Router 4 docs:
When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop (below).
render works fine both with React Loader and webpack's code splitting.
I have a very mysterious dilemma: I'm using Reducers to receive a User model from my backend. At first, the reducer returns a state of null (as expected because it's still pending the API call) and then the User model the second time around.
If that User model exists AND the customer tries to navigate to /setup, then we'll let him -- he's "authenticated". However, if he tries to access /setup and the User model doesn't exist, we redirect him back to the root path ("/").
I've made a function that will called within my App.js's Route element that checks this OAuth, called AuthenticatedRoute.js
When we get the initial value from the reducer (of null), we render the AuthenticatedRoute.js, see the value is null and then navigate to the root path. The problem is, when I get the SECOND value from the reducer (of the user model), the AuthenticatedRoute.js doesn't try to re-render at all. Isn't it suppose to? The state of the prop in App.js (the parent component) changed. It's "suppose" to check so we can check if the User model came back and if the customer is allowed to go to the /setup page.
App.js (parent component that contains the Route):
class App extends Component {
state = { isUserSetUp: false }
// If User exists AND its isProfileSetUp is true then change state to TRUE
componentWillReceiveProps(nextProps) {
if (nextProps.auth && nextProps.auth.isProfileSetUp) {
this.setState({ isUserSetUp: false }, function() {
console.log("This is when we receive the User model from the reducer");
});
}
else {
this.setState({ isUserSetUp: false });
}
}
// Upon mount of this component, we receive the User via a reducer endpoint
componentDidMount() {
this.props.fetchUser();
}
render() {
return (
<div className="container">
<BrowserRouter>
<div>
<Header />
<Route exact path="/" component={Landing} />
<Route exact path="/dashboard" component={Dashboard} />
{/* Profile Set up... This is using our AuthenticatedRoute*/}
<Route exact path="/setup" component={AuthenticatedRoute(Setup, this.state.isUserSetUp, Landing)} />
</div>
</BrowserRouter>
</div>
);
}
};
And here is the AuthenticatedRoute:
import React from 'react';
import { withRouter } from 'react-router';
import { Redirect } from "react-router-dom";
export default function requireAuth(Component, isAuthenticated, Landing) {
class AuthenticatedComponent extends React.Component {
componentWillMount() {
this.checkAuth();
}
// We call this only the first time...never the second time around
checkAuth() {
console.log("This is when we run the AuthenticatedRoute");
if (!isAuthenticated) {
// For some reason when this hits, I no longer get the second value (User model) from the reducer. WITHOUT it, I get the second value in this component.
this.props.history.push('/');
}
}
render() {
return isAuthenticated
? <Component { ...this.props } />
: null;
}
}
return withRouter(AuthenticatedComponent);
}
NOTE:
So without the "this.props.history.push('/') within the AuthenticatedRoute, I RECEIVE the second reducer response (I tried console.logging it from the AuthenticatedRoute's render() method)...But the moment I handle the reducer's first response with the this.props.history.push, I never get the second response.
Same deal if I use a within the:
render() {
return isAuthenticated
? <Component { ...this.props } />
: null;
}
Do you guys have any idea? This is too weird.