Tengo esta clase que se supone que debe autenticar a un usuario (en este caso, un moderador)
import Cookie from "universal-cookie"; import { promiseNotification, updateNotification } from "./addNotification"; const cookies = new Cookie(); class Authentication { token; role; login = (username, password) => { const id = promiseNotification("Login...") fetch("auth/get-token", { method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify({username: username, password: password}) }) .then(res => res.json()) .then(data => { updateNotification(id, data); if (data.token) { cookies.set("token", data.token); this.setToken(); return this.setRole(); //If I understand correctly this returns a promise } }).then(() => window.location.replace("/mod")) //and this handles the setRole promise .catch((error) => {alert("Error occurred login in"); console.log(error)}); } setRole = async () => { return fetch(`/auth/get-role/${this.token}`, {method: 'GET'}).then(res => res.json()) .then(data => this.role = data.role); } setToken = () => { this.token = cookies.get("token") || ""; } } export default new Authentication();
Cuando llamo a la función de inicio de sesión, el rol y el token deben configurarse en la instancia de clase y, una vez que finaliza, debe redirigir al usuario a la página de modificaciones. En la página de mods tengo esta lógica para evitar que los no moderadores accedan a ella.
useEffect(() => { console.log(JSON.stringify(auth)); //This prints an empty object, meaning that none of the actions that happened in login had any effect if (!["administrator", "moderator"].includes(auth.role)) { createNotification("You are not a moderator", "error"); history.push("/admin-login"); } }, []);
¿Por qué no se actualiza ninguna de las propiedades del objeto de autenticación?