Search code examples
javascriptpromisefetch

How do I use the result of fetch() multiple time without it becoming undefined? (new to JS)


I have some basic code that uses fetch() to get a json from an api. Then I "sort" (idk if thats the right word) through the "layers" (again don't know the word) to get (for example) the number of kills they have gotten in a certain gamemode on a minecraft server. The problem is I would like to check another stat, for example games played. I can't just get the data from the api again because you can only get data on each player once per minute. The problem is when I try to use the result from the fetch() again it doesn't work as the promise has been fulfilled I think (I am really new to Java Script). Here is the code:

<body>
    <form>
        <label for="fname">Username:</label><br>
        <input type="text" id="username" name="username"><br>
    </form>

    <p class="costs" id="kills">Hello!</p>

    <script>
        function BedwarsKills() {
            var queryString = location.search; // Returns:'?q=123'
            let params = new URLSearchParams(queryString);
            let q = params.get("username"); // is the number 123
            console.log(q)

            url = "https://api.hypixel.net/player?name="+q+"&key=d3a8fade-b2e6-4a3b-8239-e11a1c9a52d4"
            console.log(url)
            fetch(url)
                .then(response => response.json())
                .then(data => data.player.stats.Bedwars.kills_bedwars)
                .then(data => document.getElementById("kills").innerHTML = q + " has " + data + " kills")
        }
        BedwarsKills()
    </script>       
</body>

Just to clarify I would like to add something else like these 2 lines

                .then(data => data.player.stats.Bedwars.kills_bedwars)
                .then(data => document.getElementById("kills").innerHTML = q + " has " + data + " kills")

but using wins_bedwars in the place of kills_bedwars using the same fetch thing. Any ideas?

(let me know if you need to know anything else)


Solution

  • You shouldn't use two .then() calls for synchronous functions. You can achieve the same with a single callback function and a local variable:

    fetch(url)
    .then(response => response.json())
    .then(data => {
         const kills = data.player.stats.Bedwars.kills_bedwars;
         document.getElementById("kills").innerHTML = q + " has " + kills + " kills");
    });
    

    You can easily put multiple statements in the function - as many as you want, including some for wins_bedwars in addition to those for kills_bedwars.