D
D
d22072020-08-20 20:50:57
React
d2207, 2020-08-20 20:50:57

How to redirect when logging in?

Good afternoon! The navbar has two buttons - login or logout. Logout works fine, which can not be said about the login. When a user passes authorization, he must get to a certain page, but remains on the authorization page. How does it work ? It looks like it's normal without a redirect. P/S: This is a pet project without a backend with registration and obtaining access rights, so I simulate all this on the front. LOGINwindow.location.href = "/additem"reload();

export function Login() {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    
    function onChangeUsername(e) {
        setUsername(e.target.value)
    }

    function onChangePassword(e) {
        setPassword(e.target.value)
    }

    function getToken() {
        const token = Date.now().toString();
        if (username && password) {
            localStorage.setItem('userToken', JSON.stringify(token))
        }
        ChangeLocation()
    }

     function ChangeLocation() {
         window.location.href = 'http://localhost:3000/additem'
     }

    return (...)


LOGOUT
export function Navigbar() {
    const [currentUser, setCurrentUser] = useState(undefined);

    useEffect(() => {
        Authentication();
    });

    function Authentication() {
        setCurrentUser(localStorage.getItem('userToken'));
    }

    function LogOut() {
        localStorage.removeItem('userToken');
        ChangeLocation();
    }

    function ChangeLocation() {
        window.location.reload()
    }

    return (...)


ROUTE
return (
        <Switch>
            <Route exact path="/" render = {() => <Redirect to="/login"/>}/>
            <Route exact path="/login" component={Login}/>
            <Route path="/additem" render={() => isLoggedIn ? <AddItem/> : <Redirect to="/login"/>}/>
            <Route path="/edititem" render={() => isLoggedIn ? <EditUsers/> : <Redirect to="/login"/>}/>
            <Route path="/deleteitem" render={() => isLoggedIn ? <DeleteItem/> : <Redirect to="/login"/>}/>
            <Route exact path="/listOfItem" component={ListOfItems}/>
            <Route path="/listOfItem/:personId" component={ItemPage}/>
        </Switch>
    )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-08-20
@hzzzzl

import { Redirect } from "react-router-dom";

export function Login() {
    const [isAuthed, setIsAuthed] = useState(false)     // !

    function getToken() {
        const token = Date.now().toString();
        if (username && password) {
            localStorage.setItem('userToken', JSON.stringify(token))
            setIsAuthed(true)   // !
        }
    }

     if (isAuthed) return <Redirect to="/additem" />   //  !!!

    return (...)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question