Reputation: 11
I was wondering how to get a string from this fetch. I have this code so far, for example, I want the level like
message.reply(`Your level is ${level}`)
Right now I have this code:
if(args[0]) {
let krunkerName = args[0]
const api = `https://apiktracer.herokuapp.com/user/${krunkerName}`;
fetch(api)
.then(res => res.text())
.then(body => console.log(body));
message.channel.send() //String here
} else {
message.reply("Please select a user to check stats on")
}
From the console.log
, I get this right now when i type in a name, in this example mackex5x5
:
{"stats":{"name":"mackex5x5","id":2858585,"score":2921985,"level":51,"levelProgress":28,"kills":25913,"deaths":5309,"kdr":"4.88","kpg":"19.92","spk":"112.76","totalGamesPlayed":1301,"wins":922,"loses":379,"wl":"0.71","playTime":"3d 26m","funds":22280,"clan":false,"featured":"No","hacker":false,"following":0,"followers":3,"shots":186973,"hits":72936,"nukes":71,"meleeKills":59,"createdDate":"2019-04-13","createdTime":"13:06:00","lastPlayedClass":"Marksman"},"uuid":"3e78ef6b-6121-42db-a112-e6757e5d0bf4","error":"False"}
Upvotes: 0
Views: 102
Reputation: 12542
You want the .send
or .reply
in your .then
chain.
if(args[0]) {
let krunkerName = args[0]
const api = `https://apiktracer.herokuapp.com/user/${krunkerName}`;
fetch(api)
.then(res => res.json())
.then(body => {
console.log(body)
message.reply(`Your level is ${body.stats.level}`) //String here
});
}else{
message.reply("Please select a user to check stats on")
}
Because the fetch
api is resolving in the future as it is an asynchronous call, so message.channel.send
or message.reply
is being called BEFORE it resolves.
Upvotes: 2
Reputation: 1552
Are you just asking how you could access data within an object in JavaScript? If so, you should be converting the fetch
response to a JavaScript object with json()
(rather than parsing it as text
):
fetch(api)
.then(res => res.json()) // change text() to json()
.then(body => message.reply(`Your level is ${body.stats.level}`));
Upvotes: 1
Reputation: 54
Access the properties of the object being returned using dot syntax. console.log(body)
would become console.log(body.stats.level)
.
Upvotes: -1