J
J
Jorlian2020-07-19 13:42:41
React
Jorlian, 2020-07-19 13:42:41

PrivateRoute how to implement token validation?

Hello!
The question is how to make a request for a back in PrivateRoute and, depending on the answer, render the page!

App Component

export default function App() {
    return (
        <Router>
            <div>
                <Switch>
                    <Route path="/login">
                        <LoginPage />
                    </Route>
                    <PrivateRoute path="/messenger">
                        <Messenger />
                    </PrivateRoute>
                </Switch>
            </div>
        </Router>
    );
}


private route
function PrivateRoute({children, ...rest}) {
    return (
        <Route
            {...rest}
            render={({location}) =>
                tokenStatus ? (
                    children
                ) : (
                    <Redirect
                        to={{
                            pathname: "/login",
                            state: {from: location}
                        }}
                    />
                )
            }
        />
    );
}


It turns out that I need to make such a request for backing
let token = Cookies.get('token');
        isTokenValid(token)
            .then(response => {
                    if (response.ok) {
                        // tokenStatus = true или вызов action
                    }
                }
            )
    }


export  function isTokenValid(token) {
    return  fetch(`${Url}:${Port}/is-token-valid`, {
        method: 'POST',
        body: JSON.stringify(token)
    })
}


and if the answer is 200 then change tokenStatus to true and render /messenger
by default tokenStatus = false and /login is rendered
the essence of the question is this, I don’t know where to call the request so that tokenStatus has already changed before rendering

When login, the response returns a token and is written to Cookie

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-07-19
@Robur

this should be done not in PrivateRoute, but somewhere else (for example, at the start of the application, or after login) and put it in the application state.
PrivateRoute should just look at the state - it can be shown or not, it should not make any requests.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question