-1

As you can see, I'm using a login form that validates user and password online, generates a token and is supposed to redirect the user to a pacientes.html page once the token exists.

The problem starts in renderApp. It does execute the window.location.href, but in order to redirect, I have to manually refresh the page. Am I doing anything wrong?

let ruta = 'login'

const renderApp = () =>{
    const token = localStorage.getItem('token')
    if (token) {
        window.location.href = "pacientes.html"

    }
}

window.onload= () => {
    renderApp()
    const loginForm= document.getElementById('login')
    loginForm.onsubmit = (e) =>{
        e.preventDefault()
        e.stopPropagation()
        const cedula = document.getElementById('cedula').value
        const password = document.getElementById('password').value

        fetch('https://janfa.gharsnull.now.sh/api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({cedula, password})
        }).then( x => x.json())
          .then( respuesta => {
            localStorage.setItem('token' , respuesta.token)
            ruta = 'users'
          })
    }

}  
Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37

1 Answers1

0

If you want to redirect when you get the response from the HTTP request, then put the code to redirect in the then callback.

i.e. replace ruta = 'users' with location.href = "pacientes.html".

If you put it in the render function, it will only get executed when the component renders!

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335