删除属性后如何更新HTML对象

The purpose of the code is to evaluate an item from the localStorage and if it is defined, makes a <p></p> visible. But when it enters to if(error) the hidden attribute is removed but the <p></p> doesn't update. To see it I have to manually refresh the page. What can I do to solve this?

这是JavaScript代码:

const renderApp = () =>{
    const token = localStorage.getItem('token')
    const role = localStorage.getItem('role')
    const error = localStorage.getItem('error')
    const parrafo = document.getElementById('error')
    if (token) {
            if (role=== 'user') {
                location.href = "pacientes.html"

            }else if( role === 'medico'){
                location.href = "medico.html"
            }
        }
    if (error) {
        parrafo.removeAttribute("hidden")
    }
}


window.onload= () => {
    renderApp()
    const loginForm= document.getElementById('login')
    loginForm.onsubmit = (e) =>{    
        e.preventDefault()
        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)
            localStorage.setItem('error', respuesta.error)
            return respuesta.token
          })
          .then( token=> {
            return fetch('https://janfa.gharsnull.now.sh/api/auth/me', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    authorization : token,
                },
            })
          })
          .then( x => x.json())
          .then ( user => {
            localStorage.setItem('role', user['role'])
            renderApp()
          })
    }
}       

The function renderApp() is called when the page loads and when the form is submitted

评论
  • 清奇文
    清奇文 回复

    Could it be you're accidentally grabbing the element id of error instead of parrafo?

    const parrafo = document.getElementById('parrafo') // originally error