Search code examples
reactjsroutesreact-router-domreact-apolloaws-amplify

React-router-dom not re rendering Switch when state is change


I am using aws-amplify, react-hook in my project. The app have some private Routes has been define below:

const ProtectedRoute = ({render: C, props: childProps, ...rest}) => {  
    return (
        <Route
            {...rest}
            render={rProps =>
                (childProps) ? (
                    <C {...rProps} {...childProps} />
                ) : (
                    <Redirect
                        to={`/login?redirect=${rProps.location.pathname}${
                            rProps.location.search
                            }`}
                    />
                )
            }
        />
    );

}

In App.js, we change childProps to define whether user is login or not. But when childProps change, Switch not re rendering. What is the way to force React re rendering its Route because isAuthenticated is change but ProtectedRoute is not rerender.

const [isAuthenticated, userHasAuthenticated] = useState(null);
    useEffect(() => {
        onLoad();
    }, []);


    async function onLoad() {
        try {
            let user = await Auth.currentSession();
            if (user.accessToken.payload) {
                userHasAuthenticated(user.accessToken.payload);
            }
        } catch (e) {
            if (e !== 'No current user') {
                alert(e);
            }
        }

    }
.....
 const childProps = isAuthenticated;
 return (
 <ApolloProvider client={client} >
            <div className="App">
                <BrowserRouter>
                    <Route path='/'>
                        <div>
                            <Switch>


                                <Route path='/login' render={props => <Login {...props}/>} exact/>
                                 <ProtectedRoute
                                    exact
                                    path='/admin/:name'
                                    render={()=> <Admin  />}
                                    props={childProps}
                                />



                                <Route path='/' render={props => <User {...props} />}/>

                            </Switch>
                        </div>
                    </Route>
                </BrowserRouter>
            </div>
        </ApolloProvider>)

Solution

  • The route only renders again when you enter that URL again. You are doing a Redirect, meaning it will never have a chance to enter the same URL after authentication is complete. You should delay rendering the protected route until you have confirmed authentication:

    useEffect(() => {
        async function onLoad() {
            try {
                let user = await Auth.currentSession();
                userHasAuthenticated(!!user.accessToken.payload);
            } catch (e) {
                if (e !== 'No current user') {
                    alert(e);
                }
            }
    
        }
        onLoad();
    }, []);
    ...
    const ProtectedRoute = ({render: C, props: childProps, ...rest}) => {  
        if (childProps === null) {
            // app still waiting authentication
            return 'Loading...';
        }
    
        return (
            <Route
                {...rest}
                render={rProps =>
                    (childProps) ? (
                        <C {...rProps} {...childProps} />
                    ) : (
                        <Redirect
                            to={`/login?redirect=${rProps.location.pathname}${
                                rProps.location.search
                                }`}
                        />
                    )
                }
            />
        );
    }