cannot display fetched data in my javascript file - javascript

I have a json file and i fetched the data. However I cannot display it on the screen.
How can I display ? I get the data results in the console however I cannot reach the parametres like product name, price.
My code is below
index.html
<body>
<div id="products"></div>
<script src="/index.js"></script>
</body>
index.js
fetch("./data.json")
.then(response => {
return response.json();
})
.then(data => console.log(data));
showProducts = products => {
const showProductsDiv = document.querySelector("#products");
products.map(product => {
const productElement = document.createElement("p");
productElement.innerText = `product Name: ${product.name}`;
showProductsDiv.append(productElement);
});
}
I also share console results

You need to use your showProducts function.
Here is a sample code that will work for you too, but please, bear in mind, that I have used an example api. It's a bit different to yours that is why I have results array and name.first.
const url = 'https://randomuser.me/api/?results=10';
fetch(url)
.then((resp) => resp.json())
.then(data => {
return showProducts(data)
})
showProducts = products => {
const showProductsDiv = document.querySelector("#products");
products.results.map(product => {
const productElement = document.createElement("p");
productElement.innerText = `product Name: ${product.name.first}`;
showProductsDiv.append(productElement);
});
}

Related

JavaScript Array.filter() and .map() don't work, uncaught TypeError for Search function

So I'm trying to implement a search bar in my Flask application that will list out the cities that are being inputted by the user and exist in the JSON API results of a weather API.
I am following a tutorial and basically have the same code as ths: https://codepen.io/jamesqquick/pen/XWJxBQv
However, in my implementation, the .filter() and .map() functions don't work, I get the following error:
TypeError for map() and filter()
How do I fix this?
Here's my code (the regular generateHTML in the first part of the code with fetching current weather data already works, only the "SEARCH BAR" section has problems):
let currentType = "current.json";
let userCity = "London";
const apiData = {
url: "http://api.weatherapi.com/v1",
type: `${currentType}`,
key: "40cd513af8aa446484a92837213011",
city: `${userCity}`,
};
const { url, type, key, city } = apiData;
const apiUrl = `${url}/${type}?key=${key}&q=${city}`;
console.log("apiUrl:");
console.log(apiUrl);
fetch(apiUrl)
.then((data) => {
if (data.ok) {
return data.json();
}
throw new Error("Response not ok.");
})
.then((locationRequest) => generateHtml(locationRequest))
.catch((error) => console.error("Error:", error));
const generateHtml = (data) => {
console.log("data:")
console.log(data);
console.log("data.location.name:")
console.log(`${data.location.name}`);
const html = `
<div class="weather-location">
<h1>${data.location.name}, ${data.location.country}</h1></div>
<div class="details">
<span>Tmp: ${data.current.temp_c} °C</span>
<span>Feels like: ${data.current.feelslike_c} °C</span>
</div>
`;
const weatherDiv = document.querySelector(".weather");
weatherDiv.innerHTML = html;
};
/* SEARCH BAR */
const citiesList = document.getElementById('weather-cities');
const searchBar = document.getElementById('weather-searchbar');
let cities = [];
console.log("citiesList:");
console.log(citiesList);
console.log("searchBar:");
console.log(searchBar);
searchBar.addEventListener('keyup', (e) => {
userCity = e.target.value.toLowerCase();
console.log("usercity:");
console.log(userCity);
const filteredCities = cities.filter((city) => {
return (
city.name.toLowerCase().includes(userCity) ||
city.region.toLowerCase().includes(userCity) ||
city.country.toLowerCase().includes(userCity)
);
});
displayCities(filteredCities);
});
const loadCities = async () => {
try {
currentType = "search.json";
const res = await fetch(apiUrl);
cities = await res.json();
console.log("cities:");
console.log(cities);
displayCities(cities);
} catch (err) {
console.error(err);
}
};
const displayCities = (cities) => {
let htmlString = cities
.map((city) => {
return `
<li class="character">
<h2>${city.location.name}</h2>
<p>Temperature: ${city.current.temp_c} °C</p>
<p>Feels like:${city.current.feelslike_c} °C></p>
</li>
`;
})
.join('');
citiesList.innerHTML = htmlString;
};
loadCities();
<div class="other-stats">
<div class="weather-search">
<input type="text" id="weather-searchbar" placeholder="Your city"></input>
<ul id="weather-cities"></ul>
</div>
<div class="weather"></div>
</div>
<script src="../static/weather_api.js"></script>
Array.prototype.filter() and Array.prototype.map() are used for arrays, the cities property is getting a javascript object. You need to assign an array to "cities".
Ok, it seems I solved the issue for now. In displayCities, for the HTML section I put city.location.name like I'd do to get the name in "current.json" API call, but in the new API call "search.json" I get an array of dictionaries that contain different information directly, not with different categories like "location" or "current". So city.name is enough. To clarify better, see console.log entries:
API call "current.json"
API call "search.json"
const displayCities = (cities) => {
let htmlString = cities
.map((city) => {
return `
<li class="character">
<p>${city.name}</p>
</li>
`;
})
.join('');
citiesList.innerHTML = htmlString;
};

API search in javascript to return filtered list only

I am trying to make a filtered API search and only display the data(users) that has been filtered. However my search seems to return all the data and not just the data that has been filtered out. I can see the right data in the console log but can't seem to figure out how to get it to render on display.
For example, if I search for janet, I can see all the data that contains the name janet when I console log it but on display it still displays all the users. What am I doing wrong? Thanks
const UserList = document.getElementById('userList');
const searchBar = document.getElementById('searchBar');
let data = [];
searchBar.addEventListener('keyup', (e) => {
e.preventDefault();
const searchString = e.target.value;
console.log(e.target.value)
const filteredUsers = data.data.filter((user) => {
return (
user.first_name.includes(searchString) ||
user.email.includes(searchString)
);
});
console.log(filteredUsers)
displayUsers(filteredUsers);
});
const loadUsers = async () => {
try {
const res = await fetch('https://reqres.in/api/users');
data = await res.json();
displayUsers(data);
console.log(data)
} catch (err) {
console.error(err);
}
};
const displayUsers = (users) => {
const htmlString = data.data
.map((user) => {
return `
<li class="user">
<h2>${user.first_name}</h2>
</li>
`;
})
.join('');
userList.innerHTML = htmlString;
};
loadUsers();
On displayUsers function you are mapping on data.data variable. You should use users.map.
This might not be the problem, but you are defining UserList at the top and then using userList at the bottom, small typo maybe?

reactJS fetch json data from API

I am the new guy in the JS and reactJS.
I want to get info from API to an array. I made API that show all the info from my DB.
It looks like this :
const [tempNew, setTempNew] = useState([]);
const getAllWeatherCelsius = () => {
fetch('http://localhost:5000/weather')
.then(response => {
return response.json();
})
.then((jsonData) => {
let tmpArray = [];
for (var i = 0; i < jsonData.length; i++) {
tmpArray.push(jsonData.dayCelsius[i]) <---- here is the error
}
setTempNew(tmpArray);
})
}
Im want to collect all values from "dayCelsius" line into array.
What i need to change in this code ? Thank you :)
Can you provide more info about the error? But You can try using the map function like
const tmpArray = jsonData.map(r => r.dayCelsius);
You can use map function to return the dayCelsius value of each element and store them in the tmpArray.
let tmpArray = jsonData.map((el, i) => el.dayCelsius);
So, what I understand is that you are facing difficulty in just getting the dayCelsius value from the array of objects you fetch from your API.
It is difficult to make out what the problem is as more info about the error is required to see what is going wrong.
What I have done differently here is instead of the for-loop and jsonData.dayCelsius[i], I have used data.map((r,e) => r.dayCelsius).
const [temp, setTemp] = useState([]);
const getAllWeatherCelsius = () => {
fetch('http://localhost:5000/weather', {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
})
.then(response => {
return response.json();
})
.then((data) => {
const tempArray = data.map((r,e) => r.dayCelsius);
setTemp(tempArray);
})
.catch(err => console.log(err));
}
I hope it helps you, have a good day :)

How to display a list of element in as a list in HTML from a Javascript array from an API?

My JS code is this but I want to be able to get the moves array to be displayed in HTML in a list format, how can I go about doing so?
const getData = () => {
axios
.get(" https://pokeapi.co/api/v2/pokemon/charmander")
.then((response) => {
const stats = response.data.moves;
const moves = stats.map((obj) => {
return obj.move.name;
});
})
.catch((error) => console.log(error));
};
You can use a safe helper to populate a node in the page, let's say <div id="list"></div>, so that your code can do something like:
import {render, html} from '//unpkg.com/uhtml?module';
const getData = () => {
axios
.get(" https://pokeapi.co/api/v2/pokemon/charmander")
.then((response) => {
const stats = response.data.moves;
render(document.getElementById('list'), html`
<ul>
${stats.map((obj) => html`<li>${obj.move.name}</li>`)}
</ul>
`);
})
.catch((error) => console.log(error));
};
That will also do the right thing next time you call getData in case data changes.
Here is a proposition requiring no library (VanillaJS only) :
const getData = () => {
axios
.get(" https://pokeapi.co/api/v2/pokemon/charmander")
.then((response) => {
const stats = response.data.moves;
// Create <ul> tag
const ul = document.createElement('ul');
stats.forEach((obj) => {
// Create <li> tag
const li = document.createElement('li');
// Add text to <li>
li.textContent = obj.move.name;
// Append <li> to <ul>
ul.appendChild(li);
});
// Append <ul> somewhere in your DOM
document.getElementById('ul_parent').appendChild('ul');
})
.catch((error) => console.log(error));
};

fetching data and adding title to Json object

I would like to add title to my JSON object, the structure I wish to achieve is:
{
"posts": [
{
"title": "put title here",
"upvotes": 1234,
"score": 1000,
"num_comments": 100,
"created": "16.05.2019 12:12",
},
]
}
I was able to fetch data and put it into array of 26 elements, everything is fine but I wish to somehow add this "posts:" to be above whole rest, here is my code:
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
let posts = await res.data.children.map(el => {
let title = el.data.title;
let upvote = el.data.ups;
let score = el.data.score;
let comments = el.data.num_comments;
let created = el.data.created;
const allPosts = {title, upvote, score, comments, created}
postList.push(allPosts)
return postList
})
console.log(posts);
return posts
})
You might need to create the object like below
{propertyName:value}
const allPosts = {title:title,upvote: upvote,score: score,comments: comments, created:created}
postList.push(allPosts)
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json())
.then(async res => {
console.log(res);
let posts = await res.data.children.map(el => {
let title = el.data.title;
let upvote = el.data.ups;
let score = el.data.score;
let comments = el.data.num_comments;
let created = el.data.created;
const allPosts = { title, upvote, score, comments, created };
let postList = [];
postList.push(allPosts);
return postList;
});
console.log({"posts": posts});
return {"posts": posts};
});
You can try out the following code.
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json())
.then(res => ({
posts: res.data.children.map(el => ({
title: el.data.title,
upvote: el.data.upvote,
score: el.data.score,
comments: el.data.num_comments,
created: el.data.created
}))
}))
.then(posts => {
console.log(posts);
});
You can do it in this way:
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
let posts = await res.data.children.map(el => {
return {
title: el.data.title,
upvote: el.data.ups,
score: el.data.score,
comments: el.data.num_comments,
created: el.data.created
}
})
const postObject = { posts }
console.log(postObject);
return postObject
})
Map function return value, in this way you get an object with key (posts) and values (an object with details).

Categories

Resources