I have written a javascript to fetch API but it is not working can anyone please see that is there any error in my javascript. I have given some parts of my javascript which I think has error.
MY JAVASCRIPT
const redraw = () => {
resultEl.innerHTML = '';
const paged = pageResponse(results, getPageSize(), getCurrPage());
const contents = document.createElement('div');
contents.innerHTML = paged.map(record => `<div class='latestatus'><p class='copytxt'>${record.status}</p><div> <button class="copystatus btn">Copy</button></div></div>`).join('');
resultEl.append(contents);
};
//Fetch API
const retrieveAllStatus = async function() {
// write your asynchronous fetching here
// here we are making a network call to your api
const response = await fetch('https://goodman456.000webhostapp.com/api.php');
// then converting it to json instead of a readable stream
const data = await response.json();
// finally go over the array and return new object with renamed key
const results = data.map(val => ({val.status}));
return results;
}
Please just once visit the link below. It's my request.
https://goodman456.000webhostapp.com/api.php
I would make your work easy, My friends said that the below section
contents.innerHTML = paged.map(record => `<div class='latestatus'><p class='copytxt'>${record.status}</p><div> <button class="copystatus btn">Copy</button></div></div>`).join('');
resultEl.append(contents);
};
Especially the {$record.status} where I need the JSON data to be placed. My friend also said that there is something wrong in fetching API.
Please I have stucked here for a long time. And thanks in advance for those who answer this question.
Related
As the title describe my question, I just started recently developing a WhatsApp Bot using whatsapp-web.js but the problem is that i'm bad at reading documentation, so my question is :
Does anyone knows how to send anime and manga latest news to whatsapp using an api, like MyAnimeList Api or MYANIMENEWS api, or any other api
My code below which i tried :
client.on('message', async message => {
const content = message.body
if (content === "anime-news") {
const animeDb = await axios("https://cdn.animenewsnetwork.com/encyclopedia/api.xml?anime=id")
.then(res => res.data)
client.sendMessage(message.from, await MessageMedia.fromUrl('animeDb.url'))
});
You can try use this kind of algorithm to solve your problem
function hash(string, len=10){return result} // hash the content
let currentHash;
let chatSubsCode = ["12312#c.us","1231231#g.us","etc"];
const delay = 1000;
setInterval(()=>{
// some code to request data
let data = "some response"; // <- warn: it will spam API request
let hashedData = hash(data);
if(currentHash==hashedData) return;
currentHash = hashedData;
// send
for(chatid of chatSubsCode) client.sendMessage(chatid, data);
},delay)
I am trying to fetch the weather forecast api json like I did with the current weather api, but it does not seem to work any way I try.
let inOneDay = {
fetchWeather: function(){
fetch("https://api.openweathermap.org/data/2.5/forecast?q=Dortmund&units=metric&cnt=1&appid=758fce6dd3722cf25cd213a13bbc5484"
).then(resp => resp.json())
.then(data => console.log(data));
}
};
I have no idea where I went wrong. I used the same logic to make the code below work:
let weather = {
fetchWeather: function(){
fetch("https://api.openweathermap.org/data/2.5/weather?q=Dortmund&units=metric&appid=758fce6dd3722cf25cd213a13bbc5484"
).then((response) => response.json())
.then((data) => this.displayWeather(data));
},
displayWeather: function(data){
const{icon,description} = data.weather[0];
const{temp} = data.main;
document.querySelector(".icon").src = "https://www.openweathermap.org/img/wn/" + icon + ".png";
document.querySelector(".celsius").innerText = Math.round(temp) + "°C";
document.querySelector(".desc").innerText = description;
}
}
Grateful for any ideas!
Examining the json reply from that API, it looks like the OP code expects different fields than the service provides.
const result =
{"cod":"200","message":0,"cnt":1,"list":[{"dt":1631577600,"main":{"temp":13.31,"feels_like":13.05,"temp_min":13.31,"temp_max":15.87,"pressure":1018,"sea_level":1018,"grnd_level":1007,"humidity":90,"temp_kf":-2.56},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"clouds":{"all":95},"wind":{"speed":1.42,"deg":94,"gust":2.29},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2021-09-14 00:00:00"}],"city":{"id":2935517,"name":"Dortmund","coord":{"lat":51.5167,"lon":7.45},"country":"DE","population":588462,"timezone":7200,"sunrise":1631595820,"sunset":1631641686}};
const result0 = result.list[0]; // notice .list[0]
const weather0 = result0.weather[0]; // notice weather[0]
const main = result0.main; // notice main is a sibling prop to weather
const temp = main.temp
console.log(`weather is ${JSON.stringify(weather0)}`);
console.log(`main is ${JSON.stringify(main)}`);
console.log(`temp is ${temp}`);
Be sure to check for errors before dereferencing the result. It also looks like the api provides a cnt prop which might indicate the number of elements in the list.
Working on modifying a project I'm learning from.
The initial project is to create a sort of infinitely scrolling Twitter Clone. Posts were grabbed from https://jsonplaceholder.typicode.com/ api, and I'm trying to add another level by bringing in images from another image placeholder API.
I'm a noob, so I was able to successfully grab data from both API's and populate the DOM. Trouble is, with my current structure, I'm repeating placeholder images as what I'm grabbing from the placeholder api is in 5 object blocks. Could use some help in making sure every post has a different photo. Thanks, total newb here. Wondering if I should just be populating an array of objects and working from there, but maybe there's a shortcut I'm missing?
const postsContainer = document.getElementById("posts-container");
const loading = document.querySelector(".loader");
const filter = document.getElementById("filter");
let limit = 5;
let page = 1;
//Fetch Posts from API
async function getPosts() {
const res = await fetch(
`https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}`
);
const data = await res.json();
return data;
}
//Fetch Photos from another API
async function getPhoto(photo) {
const res = await fetch(`https://randomuser.me/api`);
const data = await res.json();
photo = data.results[0].picture.thumbnail;
return photo;
}
//Show items in DOM
async function showPosts() {
const posts = await getPosts();
const pic = await getPhoto();
posts.forEach((post) => {
const postEl = document.createElement("div");
postEl.classList.add("post");
postEl.innerHTML = `
<div class="number">
<img class="profile-pic" src="${pic}" alt="user photo" />
</div>
<div class="post-info">
<h2 class="post-title">${post.title}</h2>
<p class="post-body">
${post.body}
</p>
</div>
</div>
`;
postsContainer.appendChild(postEl);
});
}
//Show loader and fetch more posts
function showLoading() {
loading.classList.add("show");
setTimeout(() => {
loading.classList.remove("show");
setTimeout(() => {
page++;
showPosts();
}, 1000);
}, 300);
}
//Show initial posts
showPosts();
window.addEventListener("scroll", () => {
const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
if (scrollTop + clientHeight >= scrollHeight - 5) {
showLoading();
}
});
GitHub Repo: https://github.com/unsubstantiated-Script/infinite-scroller
TIA
Problem solved. Needed to move the pic variable inside my forEach loop. That and async the forEach loop.
I am new to web dev so please forgive.
I make simple api call
const getWorldTotal = async () => {
const response = await fetch('https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/covid-19/total');
const worldTotal = await response.json();
alert(worldTotal.total_confirmed)
document.getElementById('total') = worldTotal.total_confirmed
};
getWorldTotal()
Here is my html that i am trying to update
<div class="card text-white bg-secondary mb-3" id="total" style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title" id="total"></h4>
</div>
</div>
I get the following error
index.html:80 Uncaught (in promise) ReferenceError: Invalid left-hand
side in assignment at getWorldTotal
My question is what did i do wrong? Also is this the best way to update HTML when making api calls ?
The Document method getElementById() returns an Element object and you are trying to change it which gives you the error.
Source . Also, if you want to change the text you can use
innerText
const getWorldTotal = async () => {
const response = await fetch('https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/covid-19/total');
const worldTotal = await response.json();
alert(worldTotal.total_confirmed)
document.getElementById('total').innerText = worldTotal.total_confirmed
};
getWorldTotal()
try this:
const xURL = 'https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/covid-19/total'
, total = document.getElementById('total')
;
const getWorldTotal = async () => {
let data = await (await fetch(xURL)).json()
//console.log( 'data ', data)
total.textContent = data.total_confirmed
}
getWorldTotal()
As Rajesh and Mr Jojo stated, I think adding ".textContent" or ".innerText" after "document.getElementById('total')" will help with this.
Also, when calling the function, you can add a semicolon to end the statement. getWorldTotal() + ";". While this is optional, it can be good to get in the habit of 'strict'.
I am making a leaderboard and trying to update the axios get call every 10 seconds. Using setInterval this is achieved however how do you replace the output rather than repeating the output. https://codepen.io/zepzia/pen/YzPMLLK?editors=1010
<ol id="list"></ol>
const apiOne = 'https://jsonplaceholder.typicode.com/posts';
const list = document.querySelector('#list');
const apiCall = () => {
axios.get(apiOne)
.then(resp => {
resp.data.forEach(item => {
let output = `<li class="item">${item.title} - ${item.id}</li>`;
list.innerHTML += output;
})
})
}
apiCall();
setInterval(() => apiCall(), 10000)
After getting response from your API you need to clear list by calling:
list.innerHTML = '';
You can check also other answers in this thread - How do I clear the content of a div using JavaScript?
Updated codepen