axios.get("https://swapi.co/api/people")
.then(response => {
for(let i = 0; i < response.data.length; i++){
const h1 = document.createElement('h1')
h1.textContent = response.data[i].name
document.body.appendChild(h1)
}
})
.catch(error => console.log(error))
I am trying to get this api link to create a list in browser, showing the names. I have gotten this to work with a free api from VSchool that I was able to create myself with Post request. But now that I have Swapi in there to show Star Wars characters, nothing will show. My logic for it all hasn't changed though. Am I missing something? Thank you
You are using improper response format. Add response.results instead of response.data -
axios.get("https://swapi.co/api/people")
.then(response => {
for(let i = 0; i < response.results.length; i++){
const h1 = document.createElement('h1')
h1.textContent = response.results[i].name
document.body.appendChild(h1)
}
})
.catch(error => console.log(error))
Related
I'm using MovieDB API to create a website. I'm randomly getting movie id's and generating the genres this way. However, sometimes, an id which doesn't exist gets generated and it throws a 404 error. I want to write something like: if response == 404 then rerun my code or refresh the page. I tried writing this logic many ways but I can't seem to get it to work. Thank you in advance.
async function getAPI(api_url) {
const response = await fetch(api_url)
var data = await response.json()
var g = data.genres
let user_genre = document.getElementById("input").value
for (let i = 0; i < g.length; i++) {
console.log(g[i].name)
}
}
You can check response.ok to check if the fetch succeeded, or response.status for the exact HTTP status.
const response = await fetch(api_url);
if (!response.ok) location.reload();
you can repeat function
async function getAPI(api_url) {
const response = await fetch(api_url)
if(!response.ok) {
return getAPI(api_url)
}
var data = await response.json()
var g = data.genres
let user_genre = document.getElementById("input").value
for (let i = 0; i < g.length; i++) {
console.log(g[i].name)
}
}
I tried to get the data from the json file with javascript but it doesn't output the data
here is my code:
fetch('https://raw.githubusercontent.com/trvodi/test/main/json1.json')
.then((res) => res.json())
.then((data) => {
var json = data;
var i;
var iLength = json.data.item.length;
for (i = 0; i < iLength; i++) {
alert(json.data.item[i].FromMember);
}
}).catch((err) => {
console.log(err)
})
please help me. thank you
If you'd add the following line:
console.log(json.data.item, json.data.item.length);
You'll see that json.data.item.length is undefined because json.data.item is an object.
I'd recommend using
for (let i in json.data.item) {
let item = json.data.item[i];
console.log(item.FromMember);
}
To loop over the objects as shown in this demo:
fetch('https://raw.githubusercontent.com/trvodi/test/main/json1.json')
.then((res) => res.json())
.then((data) => {
for (let i in data.data.item) {
let item = data.data.item[i];
console.log(item.FromMember);
}
})
.catch((err) => {
console.log(err)
})
For more info about why (and alternatives) I'd choose for (let i in json.data.item), please see the following question/answer:
How to loop through a plain JavaScript object with the objects as members?
My script, this should be showing the Name of game computers in html but it does not, I have been trying so much andI betit will just be something stupid that is wrong or missing
Console says : TypeError: data is undefined
The console does show me retrieving the data works
"use strict";
window.addEventListener("load", Init);
function Init() {
fetch("https://howest-gp-wfa.github.io/st-2021-1-S2-a-wfa-pe03-Jonas-Bundervoet/api/products.json")
.then(function(response) { return response.json(); })
.then(data => console.log(data))
.then(function(data){
tester(data)
})
.catch(err => console.log(err));
window.addEventListener("load", tester);
}
My function to show data on screen (shows nothing)
function tester(data)
{
let div = document.getElementById("test");
for (var i = 0; i < data.length; i++) {
let article = document.createElement("h1");
article.innerHTML = 'Name: ' + data.GameComputers[0].Name;
div.appendChild(article);
};
}
In HTML I just have this in my body
<div id="test"></div>
console.log returns undefined
.then(data => console.log(data))
.then(function(data){
tester(data)
Your first then returns the return value of console.log which is undefined.
So your second then recieves undefined as its data.
Don't use multiple then callbacks here.
.then(function(data){
console.log(data)
tester(data)
The JSON doesn't consist of an array
The JSON you are looking at returns an object.
It doesn't have a length.
for (var i = 0; i < data.length; i++) {
… is going to fail immediately.
You've got data.GameComputers[0] so I'm guessing you want to loop over GameComputers so:
Check the length of that: i < data.GameComputers.length
Make use of i when you read it: data.GameComputers[i].Name;
I have a simple fetch function that gets data (messages from db) and putting it into an array to display it with simple vanilla JS. The thing is I am calling this function every 2 seconds in order to check for new messages. But when I do that I duplicate my messages and it keeps adding instead of replacing. I am struggling to understand what I should do to change, not add.
(a little dummy question, sorry)
const list = document.getElementById('message-list');
const getData = () => {
fetch('/messages')
.then((resp) => resp.json())
.then(function(data) {
console.log(data)
for (let i = 0; i < data.length; i++) {
const listItem = document.createElement('li');
listItem.innerText = data[i].message;
const delButton = document.createElement('button');
delButton.innerHTML = 'Delete';
delButton.addEventListener('click', ()=>{
const message_id = data[i].message_id;
deleteItem(message_id);
})
listItem.appendChild(delButton);
list.appendChild(listItem)
}
})
}
setInterval(getData,2000)
Make a Set of the message_ids processed so far, and on further calls, ignore messages matching that message_id:
const seenIds = new Set();
const getData = () => {
fetch('/messages')
.then((resp) => resp.json())
.then(function(data) {
data
.filter(({ message_id }) => !seenIds.has(seenIds))
.forEach(({ message, message_id }) => {
seenIds.add(message_id);
const listItem = document.createElement('li');
listItem.innerText = message;
const delButton = document.createElement('button');
delButton.textContent = 'Delete';
delButton.addEventListener('click', () => {
deleteItem(message_id);
});
listItem.appendChild(delButton);
list.appendChild(listItem)
});
});
};
That said, it would probably be better to change your backend so that it can filter the items for you, rather than sending objects over the net that proceed to get ignored.
I was learning react and doing some axios api call with an array. I did a code on gathering data through coinmarketcap api to learn.
So, my intention was to get the prices from the api with a hardcoded array of cryptocurrency ids and push them into an array of prices. But I ran into a problem with the prices array, as the prices were all jumbled up. I was supposed to get an array in this order
[bitcoinprice, ethereumprice, stellarprice, rippleprice]
but when I ran it in the browser, the prices came randomly and not in this order, sometimes I got my order, sometimes it didn't. I used a button which onClick called the getPrice method. Does anyone know what went wrong with my code? Thanks!
constructor(){
super();
this.state = {
cryptos:["bitcoin","ethereum","stellar","ripple"],
prices:[]
};
this.getPrice = this.getPrice.bind(this);
}
getPrice(){
const cryptos = this.state.cryptos;
console.log(cryptos);
for (var i = 0; i < cryptos.length; i++){
const cryptoUrl = 'https://api.coinmarketcap.com/v1/ticker/' + cryptos[i];
axios.get(cryptoUrl)
.then((response) => {
const data = response.data[0];
console.log(data.price_usd);
this.state.prices.push(data.price_usd);
console.log(this.state.prices);
})
.catch((error) => {
console.log(error);
});
}
}
If you want to receive the data in the order of the asynchronous calls you make, you can use Promise.all, that waits until all the promises of an array get executed and are resolved, returning the values in the order they were executed.
const cryptos = ['bitcoin', 'ethereum', 'stellar', 'ripple'];
const arr = [];
for (var i = 0; i < cryptos.length; i++){
const cryptoUrl = 'https://api.coinmarketcap.com/v1/ticker/' + cryptos[i];
arr.push(axios.get(cryptoUrl));
}
Promise.all(arr).then((response) =>
response.map(res => console.log(res.data[0].name, res.data[0].price_usd))
).catch((err) => console.log(err));
You could use a closure in the for loop to capture the value of i and use it as the index once the data is returned rather than using push:
getPrice(){
const cryptos = this.state.cryptos;
console.log(cryptos);
for (var i = 0; i < cryptos.length; i++) {
const cryptoUrl = 'https://api.coinmarketcap.com/v1/ticker/' + cryptos[i];
(function (x) {
axios.get(cryptoUrl)
.then((response) => {
const data = response.data[0];
console.log(data.price_usd);
var newPrices = this.state.prices;
newPrices[x] = data.price_usd;
this.setState({prices: newPrices});
console.log(this.state.prices);
})
.catch((error) => {
console.log(error);
});
})(i);
}
}