Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

462
Vistas
How to use fetch inside another fetch?

I have this class which is supposed to authenticate a user (in this case a moderator)

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();

When I call the login function the role and token should be set in the class instance and after it finishes it should redirect the user to the mods page. In the mods page I have this logic to prevent non moderators from accessing it.

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");
        }
    }, []);

Why aren't any of the properties in the auth object being update?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda