0

I've built my own component, which works broadly as follows:

  • Sets two variables, by pulling values from local and session storage
  • If JWT doesn't exist, then navigate user to the sign in screen
  • If JWT exists, but session storage doesn't, then verify JWT is valid. If so, set session storage and return the 'children' component.
  • If JWT exists and session storage exists, then return the children.

When I run this though, if the session storage doesn't exist (i.e. step 3 runs) then it just returns a blank screen with no error message.

If session storage is present (i.e. final step is valid), then it runs as expected - and I have absolutely no idea why.

Here's my component:

const PrivateRoute = ({ children }) => {

    let isAuthenticated = localStorage.getItem('auth')
    let hasAuth = sessionStorage.getItem('husi')


    if (!isAuthenticated) {
        return <Navigate to="/sign-in" replace />
    }

    // Check if a token exists && state of auth

    if (isAuthenticated && !hasAuth) {
            console.log("Stage 1")
            axios.post("/api/checkAuth", {
                token: JSON.parse(isAuthenticated)
            })
            .then(() => {
                console.log("Stage 2")
                sessionStorage.setItem('husi', 'indeed')
                
            })
            .then(() => {
                console.log("Stage 3")
                return children
            })
            .catch((err) => {
                localStorage.clear('auth')
                return <Navigate to="/sign-in" replace />
            })
    } else if (isAuthenticated && hasAuth) {
        console.log("Stage 4")
        return children
    }
        
}

Any feedback would be appreciated!

Jon Nicholson
  • 927
  • 1
  • 8
  • 29
  • 1
    Your stage 3 `return children` is within an inner callback function. It won't be the return value of the outer PrivateRoute function. Ditto for your catch handler. – jarmod Oct 21 '22 at 16:38
  • Then how come my sessionStorage is created? – Jon Nicholson Oct 21 '22 at 16:42
  • I would encourage you to debug the code. Your function makes an async call to axios.post(...) which will complete later. Your privateRoute function will return undefined and, later, your axios.post() call will complete, invoking the callback handler chain. – jarmod Oct 21 '22 at 16:47
  • Your function should probably return a promise which is resolved later (after you handle the post response), and the caller should await that promise. – jarmod Oct 21 '22 at 16:53
  • Related: https://stackoverflow.com/questions/48980380/returning-data-from-axios-api and https://stackoverflow.com/questions/43463989/returning-an-axios-promise-from-function – jarmod Oct 21 '22 at 17:08

0 Answers0