When I run the following code:
const root = document.querySelector('#root3');
async function fetchData(userId) {
const response = await fetch(`https://randomuser.me/api/?results=10`);
const data = await response.json();
console.log(data);
console.log(data.results);
data.results.map(item => {
root.append(`<li><img src=${item.picture.thumbnail}></li>`);
});
}
fetchData();
The result is this:
Why are those quotations there? and how can I get rid of them?
OK. You cannot use append in JavaScript.
One solution, which is working is the following:
root.innerHTML += `<li><img src=${item.picture.thumbnail}></li>`;
Related
This is probably dead simple, but I can't quite figure it out. I simply want to read the contexts of a text file into a variable. What I have is:
async function load(path) {
try {
const response = await fetch(path);
const text = await response.text();
return text;
} catch (err) {
console.error(err);
}
}
var source_text = load(source_text_path);
console.log(source_text);
To my mind, this should work but only the pending promise is returned and not the text, thought I thought it was awaiting properly.
You need to wait for the load method.
var source_text = await load(source_text_path);
OR
load(source_text_path).then(e => console.log(e))
The function is indeed awaiting as it should, but since it's async, it will always result in a Promise<things> when you return thing.
Which means you should either await it elsewhere:
var source_text = await load(source_text_path);
or then it:
load(source_text_path).then((source_text) => {
console.log(source_text);
})
I want to print the followers in my webpage, it shows up in the console, but not the html document.
the code:
async function getFollowers(user) {
const response = await fetch(`https://scratchdb.lefty.one/v3/user/info/${user}`);
let responseJson = await response.json();
const count = document.getElementById.innerHTML("123");
count = responseJson.statistics.followers;
return count;}
function pfollows(user) {
const element = document.getElementById.innerHTML("123");
const USER = user;
getFollowers(USER).then(count => {
element.textContent = `${USER} has ${count} followers right now.`;
});
}
document.getElementById.innerHTML("123") seems wrong.
You should be passing an id as a string to document.getElementById like document.getElementById("someIdHere"). innerHTML is not a function and shouldn't have parentheses or an argument after it.
count looks like it should be extracted from responseJson and returned.
pfollows looks like it might be responsible for updating the actual DOM.
Redefining user as USER is somewhat redundant.
async function getFollowers(user) {
const response = await fetch(`https://scratchdb.lefty.one/v3/user/info/${user}`);
let responseJson = await response.json();
const count = responseJson.statistics.followers;
return count;
}
function pfollows(user) {
const element = document.getElementById("123").innerHTML;
getFollowers(user).then(count => {
element.textContent = `${user} has ${count} followers right now.`;
});
}
When pfollows is called, then the element with id="123" should have its content set to the desired string. If pfollows() is not called, then nothing will happen.
There's a few more possible touchups to clean up:
responseJson can probably be a const
You can inline return count without saving it to a variable return responseJson.statistics.followers
but trying to keep the changes minimal as needed to fix the problems.
i am trying to reuse a function that will render contents anywhere i use it outside of it's birthplace.
i have this code which fetches data from API
const showData = async function(){
try{
const res = await fetch(url);
const data = await res.json();
const results = data.results;
const markup = results.map(elements =>{
(.......)
return `...html elements..`
}).join('');
}
catch(error){
console.log(error)
}
}
thing is i wanna reuse this makrup variable in some other places as well.
i tried to wrap this markup inside a function..
function generateMarkup(){
const results....and so on until the html with return statement
}
generateMarkup();
as it tried to render it like this..
display.insertAdjacentHTML('afterbegin',generateMarkup);
as you guessed,it did not work,whether i close the function with parenthesis or not.
i also tried to return markup and html elements putting it inside an array.did not work either.
or is there any other way u can reuse this code in some other places?
can you plz help?
The code is being fetched but it is not being fully displayed, as in some parts are missing
https://github.com/KushRohra/GFG_Codes/blob/master/School/Leap%20year.cpp
You can see the code here and the one being displayed below.
However full code is being displayed in the console. dont know whats the problem
async function call() {
let url = "https://api.github.com/repos/KushRohra/GFG_Codes/contents/School/Leap year.cpp";
let response = await fetch(url);
console.log(data);
s = atob(data.content);
document.getElementById("code").innerHTML = s.replace(/\n/g, '<br>').replace(/\s/g, ' ');
}
call();
<div id="code"></div>
Heres how your code should look like:
async function call() {
let url = "https://api.github.com/repos/KushRohra/GFG_Codes/contents/School/Leap year.cpp";
let response = await fetch(url);
let data = await response.json();
console.log(data);
let s = window.atob(data.content);
document.getElementById("code").innerHTML = s.replace(/\n/g, '<br>').replace(/\s/g, ' ');
}
call();
You didn't declare data variable.
you didn't asked for a response to fetch body(response data) as a JSON() nor TEXT()
for atob function you better explicitly say window.atob() instead of atob()
I'm using fetch to make API calls and everything works but in this particular instance I'm running into an issue because the API simply returns a string -- not an object.
Typically, the API returns an object and I can parse the JSON object and get what I want but in this case, I'm having trouble finding the text I'm getting from the API in the response object.
Here's what the response object looks like.
I thought I'd find the text inside the body but I can't seem to find it. Where do I look?
Using the fetch JavaScript API you can try:
response.text().then(function (text) {
// do something with the text response
});
Also take a look at the docs on fetch > response > body interface methods
ES6 Syntax:
fetch("URL")
.then(response => response.text())
.then((response) => {
console.log(response)
})
.catch(err => console.log(err))
You can do this in two different ways:
The first option is to use the response.text() method, but be aware that, at Dec/2019, its global usage is only 36.71%:
async function fetchTest() {
let response = await fetch('https://httpbin.org/encoding/utf8');
let responseText = await response.text();
document.getElementById('result').innerHTML = responseText;
}
(async() => {
await fetchTest();
})();
<div id="result"></div>
The second option is to use the response.body property instead, which requires a little more work but has 73.94% of global usage:
async function fetchTest() {
let response = await fetch('https://httpbin.org/encoding/utf8');
let responseText = await getTextFromStream(response.body);
document.getElementById('result').innerHTML = responseText;
}
async function getTextFromStream(readableStream) {
let reader = readableStream.getReader();
let utf8Decoder = new TextDecoder();
let nextChunk;
let resultStr = '';
while (!(nextChunk = await reader.read()).done) {
let partialData = nextChunk.value;
resultStr += utf8Decoder.decode(partialData);
}
return resultStr;
}
(async() => {
await fetchTest();
})();
<div id="result"></div>