Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

461
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda