I'm new to async and await. I'm working on a recipe website using an api and fetch. need help to add async await to the fetch. I'm using spoonacular api.
there are no errors just want to add async await.
function retrieve(e) {
newsList.innerHTML = "";
e.preventDefault();
const apiKey = "my api key";
let topic = input.value;
let url = `https://api.spoonacular.com/recipes/complexSearch?query=${topic}&apiKey=${apiKey}&cuisine=&fillIngredients=false&addRecipeInformation=true&maxReadyTime=120&ignorePantry=flase&number=20&intolerances=gluten&sourceUrl=http://www.foodista.com`;
fetch(url)
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
data.results.forEach((results) => {
let li = document.createElement("li");
let a = document.createElement("a");
let div = document.createElement("div");
let img = document.createElement("img");
let btn = document.createElement("button");
// styling
div.className = "newsdiv";
img.className = "newsimg";
btn.className = "btns";
li.style.width = "300px";
a.setAttribute("href", results.sourceUrl);
a.setAttribute("target", "_blank");
img.setAttribute("src", results.image);
div.textContent = results.title;
// btn.prepend(br);
div.appendChild(a);
div.prepend(img);
li.prepend(div);
btn.textContent = "Get Recipe";
div.appendChild(btn);
a.appendChild(btn);
newsList.appendChild(li);
});
})
.catch((error) => {
console.log(error);
});
}
Look at below snippet. This will be useful to your solution. In the function you may do whatever operations you want.
const retrieve = async (e) => {
newsList.innerHTML = "";
e.preventDefault();
const apiKey = "my api key";
let topic = input.value;
let url = `https://api.spoonacular.com/recipes/complexSearch?query=${topic}&apiKey=${apiKey}&cuisine=&fillIngredients=false&addRecipeInformation=true&maxReadyTime=120&ignorePantry=flase&number=20&intolerances=gluten&sourceUrl=http://www.foodista.com`;
const response = await fetch(url);
const myJson = await response.json(); //extract JSON from the http response
console.log(myjson);
}
retrieve(null);
Related
How I can make this
var imageurl = 'https://tr.wikipedia.org/wiki/'
let queryimage = `${imageurl}Dosya:${cityName}.jpg`
console.log(queryimage)
When ı look console ı see this ;
https://tr.wikipedia.org/wiki/Dosya:england.jpg
thats ok but now
How ı can download image on this page https://tr.wikipedia.org/wiki/Dosya:england.jpg
This is your way :
// Your url must be like this : 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/England.jpg/800px-England.jpg'
let cityName = 'England';
let imageurl = 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/'
let queryimage = `${imageurl}${cityName}.jpg/800px-${cityName}.jpg`
let img = document.getElementById('image');
img.setAttribute('src',queryimage)
You can use MediaWiki's Action API to retrieve information about the images in these pages and grab the source of this image.
async function grabImageInfo(pageTitle) {
const resp = await fetch(`https://tr.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=${pageTitle}&piprop=original&format=json&origin=*`);
if (!resp.ok) {
throw new Error("Network Error");
}
return resp.json();
}
async function grabImageSource(pageTitle) {
const imageInfo = await grabImageInfo(pageTitle);
return Object.values(imageInfo.query.pages)[0].original.source;
}
const select = document.querySelector("select");
const img = document.querySelector("img");
const a = document.querySelector("a");
async function handleChange() {
try {
const pageTitle = `Dosya:${select.value}.jpg`;
const imgUrl = await grabImageSource(pageTitle);
img.src = imgUrl;
a.href = `https://tr.wikipedia.org/wiki/${pageTitle}`
}
catch(err) {
console.error(err);
}
}
select.onchange = handleChange;
handleChange();
<select>
<option>England</option>
<option>Italy</option>
<option>Germany</option>
<option>Flower</option>
<option>Cat</option>
</select><br>
<a>Go to Wikipedia's page</a><br>
<img>
I am trying to add the link on the image or title. when I click on the image/text it should take me to another page index.html.
How can I do that?
const apiUrl = 'https://api.themoviedb.org/3/discover/movie
sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1;
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI = "https://api.themoviedb.org/3/search/movie?
&api_key=04c35731a5ee918f014970082a0088b1&query=";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
showMovies(apiUrl);
function showMovies(url){
fetch(url).then(res => res.json())
.then(function(data){
console.log(data.results);
data.results.forEach(element => {
const el = document.createElement('div');
const image = document.createElement('img');
const text = document.createElement('h2');
text.innerHTML = `${element.title}`;
image.src = IMGPATH + element.poster_path;
el.appendChild(image);
el.appendChild(text);
main.appendChild(el);
});
});
}
form.addEventListener("submit", (e) => {
e.preventDefault();
main.innerHTML = '';
const searchTerm = search.value;
if (searchTerm) {
showMovies(SEARCHAPI + searchTerm);
search.value = "";
}
});
Fixed your code, the tick was to add a element instead of with the desired href
const apiUrl =
"https://api.themoviedb.org/3/discover/moviesort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1";
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI =
"https://api.themoviedb.org/3/search/movie? &api_key=04c35731a5ee918f014970082a0088b1&query=";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
showMovies(apiUrl);
function showMovies(url) {
fetch(url)
.then((res) => res.json())
.then(function (data) {
console.log(data.results);
data.results.forEach((element) => {
el = document.createElement("a");
el.href = "https://example.com"
const image = document.createElement("img");
const text = document.createElement("h2");
text.innerHTML = `${element.title}`;
image.src = IMGPATH + element.poster_path;
el.appendChild(image);
el.appendChild(text);
main.appendChild(el);
});
});
}
form.addEventListener("submit", (e) => {
e.preventDefault();
main.innerHTML = "";
const searchTerm = search.value;
if (searchTerm) {
showMovies(SEARCHAPI + searchTerm);
search.value = "";
}
});
I have the src (data) of an image, that is not saved yet and doesn't have a path yet.
I would like to know the future ipfs hash that will result from it once it is saved and sent to ipfs.
So far I have done this, but the hashes don't match.
import { saveAs } from 'file-saver';
const dagPB = require('ipld-dag-pb')
const UnixFS = require('ipfs-unixfs')
func = async () => {
let bgImage = await import(`./images/bg.png`);
let bodyImage = await import(`./images/body.png`);
let headImage = await import(`./images/head.png`);
let eyesImage = await import(`./images/eye.png`);
let mouthImage = await import(`./images/mouth.png`);
let levelImage = await import(`./images/level.png`);
src = await mergeImages([
bgImage.default,
bodyImage.default,
headImage.default,
eyesImage.default,
mouthImage.default,
levelImage.default,
]);
image.src = src;
saveAs(image.src, `photo.png`);
const fileBuffer = Buffer.from(image.src)
const file = new UnixFS('file', fileBuffer)
dagPB.DAGNode.create(file.marshal(), (err, node) => {
if(err) return console.error(err)
console.log(node._cid.toBaseEncodedString())
})
}
What is missing or wrong ?
And here is what I did.
const Hash = require('ipfs-only-hash')
func = async () => {
let bgImage = await import(`./images/bg${ex}.png`);
let bodyImage = await import(`./images/body${ex}.png`);
let headImage = await import(`./images/head${ex}.png`);
let eyesImage = await import(`./images/eye${ex}.png`);
let mouthImage = await import(`./images/mouth${ex}.png`);
let levelImage = await import(`./images/level${ex}.png`);
src = await mergeImages([
bgImage.default,
bodyImage.default,
headImage.default,
eyesImage.default,
mouthImage.default,
levelImage.default,
]);
const endOfPrefix = src.indexOf(",");
const cleanStrData = src.slice(endOfPrefix+1);
const imageData = Buffer.from(cleanStrData, "base64");
const imageHash = await Hash.of(imageData);
console.log("fetch data CID: " + imageHash)
}
Remove the header of the data, to keep only the data and then hash it it with ipfs-hash-only.
The image hash is then written in the .json and the same process is used to hash the .json and know before hand the metadata's ipfs address.
I have put the code below my for a simple weather app using Open Weather
The code to get the icon code from the JSON works in the first block but not in the second?
i can console log the variable no problem but when i am trying to display the icon it isnt loading the png file?
The line in question is
let icon1 = jsonResponse.list[8].weather[0].icon
nextDayWeather.src = `/resources/icons/${icon1}.png`
full code for reference including same code working in an earlier function
async function getWeather(input) {
const city = input
try {
const response = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=`)
if (response.ok) {
const jsonResponse = await response.json()
const {icon} = jsonResponse.weather[0]
currTemp.innerText = Math.floor(jsonResponse.main.temp - 273)
currWind.innerText = jsonResponse.wind.speed
currWeather.src = `/resources/icons/${icon}.png`
return
}
throw new Error('Request Failed')
} catch(error) {
window.location = '/'
}
}
async function extraWeather(input) {
const city = input
try {
const response = await fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=`)
if (response.ok){
const jsonResponse = await response.json()
let icon1 = jsonResponse.list[8].weather[0].icon
let icon2 = jsonResponse.list[16].weather[0].icon
let icon3 = jsonResponse.list[24].weather[0].icon
nextDayWeather.src = `/resources/icons/${icon1}.png` //needs fixing??
nextDayWind.innerText = jsonResponse.list[8].wind.speed
nextDayTemp.innerText = Math.floor(jsonResponse.list[8].main.temp - 273)
nextDayWeather2.src = `/resources/icons/${icon2}.png`
nextDayWind2.innerText = jsonResponse.list[16].wind.speed
nextDayTemp2.innerText = Math.floor(jsonResponse.list[16].main.temp - 273)
nextDayWeather3.src = `/resources/icons/${icon3}.png`
nextDayWind3.innerText = jsonResponse.list[24].wind.speed
nextDayTemp3.innerText = Math.floor(jsonResponse.list[24].main.temp - 273)
console.log(jsonResponse.list[16].weather[0].icon)
return
}
throw new Error ('error') }
catch(error){
console.log(error)
}
}
I'm trying to change a global variable from inside a click event listener. However the variable fails to change once button is clicked. The objective here is to change a URL for a fetch request.
// Default URL
var url = 'https://newsapi.org/v2/top-headlines?sources=bbc-news&Apikey123';
var req = new Request(url);
// Event Listener - Change URL
document.getElementById('btn').addEventListener('click', function() {
var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
var req = new Request(url);
sendRequest();
})
// Fetch Data from API
function sendRequest() {
fetch(req)
.then(r => r.json())
.then(r => {
const container = document.getElementsByClassName('post-container')[0];
for(i = 0; i < 5 ; i++) {
// Create post elements
const post = document.createElement('div');
const postHeader = document.createElement('div');
const postBody = document.createElement('div');
// Set ID
post.id = 'post';
postHeader.id = 'post-header';
postBody.id = 'post-body';
// Append Elements
container.appendChild(post);
post.appendChild(postHeader);
post.appendChild(postBody);
// Post title data from array into div
let article = r.articles[i];
let title = article.title;
let content = article.description;
postHeader.innerHTML = title;
postBody.innerHTML = content;
}
console.log(container);
});
}
sendRequest();
To solve the problem:
...
document.getElementById('btn').addEventListener('click', function() {
var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
// Don't use var, becouse it's variable have scope in current function
// var req = new Request(url);
req = new Request(url);
sendRequest();
})
...
But better send param to sendRequest:
...
// Event Listener - Change URL
document.getElementById('btn').addEventListener('click', function() {
var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
var req = new Request(url);
sendRequest(req); // <--- set param
})
// Fetch Data from API
function sendRequest(req) { // <--- get param
...
});
...
Remove the var from inside the Event Listener
document.getElementById('btn').addEventListener('click', function()
{
url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
var req = new Request(url);
sendRequest();
})
The thing is you are declaring the var url twice , and var req twice
the first one at the begining of your code and the second one in your event listner ,
try this
var url = 'https://newsapi.org/v2/top-headlines?sources=bbc-news&Apikey123';
var req = new Request(url);
// Event Listener - Change URL
document.getElementById('btn').addEventListener('click', function() {
url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
req = new Request(url);
sendRequest();
})
// Fetch Data from API
function sendRequest() {
fetch(req)
.then(r => r.json())
.then(r => {
const container = document.getElementsByClassName('post-container')[0];
for(i = 0; i < 5 ; i++) {
// Create post elements
const post = document.createElement('div');
const postHeader = document.createElement('div');
const postBody = document.createElement('div');
// Set ID
post.id = 'post';
postHeader.id = 'post-header';
postBody.id = 'post-body';
// Append Elements
container.appendChild(post);
post.appendChild(postHeader);
post.appendChild(postBody);
// Post title data from array into div
let article = r.articles[i];
let title = article.title;
let content = article.description;
postHeader.innerHTML = title;
postBody.innerHTML = content;
}
console.log(container);
});
}
sendRequest();