0

I am working on a React project. I tried to create a protected route component for the React application that I am building, but I am not sure why I can get response.status print properly but cannot get the component return properly. Can anybody please help?

import React from 'react';
import { Route, Redirect } from 'react-router-dom';


function ProtectedRoute({ component: Component, ...rest }) {

    return (
        <Route {...rest} render={(props) => {

            const identity = JSON.parse(localStorage.getItem('identity'));

            if (identity !== null && identity !== undefined) {
                if (identity.id !== null && identity.email !== null && identity.id !== undefined && identity.email !== undefined) {
                    
                    // Check with backend
                    Api.get('/checkProtection', {
                        withCredentials: true,
                        headers: {
                            'identity': localStorage.getItem('identity')
                        }
                    }).then((response) => {
                        console.log(response.status);
                        return (
                            <Component />
                        );
                    }).catch((error) => {
                        console.log(error);
                        return (
                            <Redirect to={{ pathname:'/login', state: {from: props.location} }} />
                        );
                    });


                } else {
                    return (
                        <Redirect to={{ pathname:'/login', state: {from: props.location} }} />
                    );
                }
            } else {
                return (
                    <Redirect to={{ pathname:'/login', state: {from: props.location} }} />
                );
            }
        }}
        />
    );
}


export default ProtectedRoute;

1 Answer 1

1

You are trying to return the component from callback function of then(), when what you should be doing is returning it from the render prop callback function.

The solution below, although untested, might work.

import React, { useState, useEffect } from 'react';
import { Route, Redirect } from 'react-router-dom';

function HandleResponse({ location }) {
    const [result, setResult] = useState('');

    useEffect(() => {
        const identity = JSON.parse(localStorage.getItem('identity'));
        if (identity === null || identity === undefined) {
            setResult('redirect')
        }

        if (identity.id === null 
            || identity.email === null 
            || identity.id === undefined 
            || identity.email === undefined
        ) {
            setResult('redirect')
        }

        // Check with backend
        Api.get('/checkProtection', {
            withCredentials: true,
            headers: {
                'identity': localStorage.getItem('identity')
            }
        }).then((response) => {
            console.log(response.status);
            setResult('success');
        }).catch((error) => {
            console.log(error);
            setResult('redirect');
        });
    }, [])

    if (result === 'success') {
        return <Component />
    }

    if (result === 'redirect') {
        return <Redirect to={{ pathname:'/login', state: {from: location} }} />
    }

    return null;
}

function ProtectedRoute({ component: Component, ...rest }) {
    return (
        <Route {...rest} render={(props) => <HandleResponse {...props} />}
        />
    );
}

export default ProtectedRoute;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.