Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

460
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!