problem taking the value of getElementByID - javascript

var baseUrl = "https://pokeapi.co/api/v2/pokemon/";
var pokemonid = document.getElementById('pokemon_id').value;
function fetchPokemon(){
fetch(`${baseUrl}&{pokemonid}`)
.then(response => {
return response.json()
})
.then(data => {
console.log(data);
})
}
fetchPokemon();
This code return me https://pokeapi.co/api/v2/pokemon/?offset=20&limit=20' at url, how can I change pokeomonid.value for return the number or name on the input?

i solve my problem using async await:
const insertPokemon = async(a) => {
const respuesta = await fetch('https://pokeapi.co/api/v2/pokemon/'+a)
const data = await respuesta.json()
const {value} = data
console.log(data)
nombre.textContent = data.name
id.textContent = "ID_"+data.id
img.src = data.sprites.front_default
pokeTypes.textContent = data.types[0].type.name;
pokeTypes2.textContent = data.types[1].type.name;
stats(value)
}
form.addEventListener('submit', (event) =>{
event.preventDefault();
pokeTypes.textContent = "";
pokeTypes2.textContent = "";
insertPokemon(pokeselect.value.toLowerCase());
})

Related

How can I store the data in arrow function?

Here is my arrow function I am storing in this let s arrow function,
which I stored inside of a loop and merged all object in object.assign. When I run the let s arrow function, however, I'm getting a Promise { undefined } error.
let s = async() => {
Object.values(sqlQuery).map(async(o:any) => {
a.map(async(k:any) => {
c.map(async(l:any) => {
var district:any = `select slug from foa_section_content where foa_section_content_id IN (${k})`;
var [district1]: any = await connection.execute(district);
var commune:any = `select slug from foa_section_content where foa_section_content_id IN (${l})`;
var [commune1]: any = await connection.execute(commune);
s = await (Object.assign(o,{district1},{commune1}))
})
})
})
}
return (s());
The issue is that you are not returning a value from the arrow function. The syntax for an arrow function is:
let s = async() => {
return Object.values(sqlQuery).map(async(o:any) => {
a.map(async(k:any) => {
c.map(async(l:any) => {
var district:any = `select slug from foa_section_content where foa_section_content_id IN (${k})`;
var [district1]: any = await connection.execute(district);
var commune:any = `select slug from foa_section_content where foa_section_content_id IN (${l})`;
var [commune1]: any = await connection.execute(commune);
return Object.assign(o,{district1},{commune1});
})
})
});
}

How to get instagram photos without using the new api

I am trying to figure out a method to grab instagram photos without the new API. Here is some code that did not return anything:
const instagramRegExp = new RegExp(/<script
type="text\/javascript">window\._sharedData = (.*);<\/script>/)
const fetchInstagramPhotos = async (accountUrl) => {
const response = await axios.get(accountUrl)
const json = JSON.parse(response.data.match(instagramRegExp)[1])
const edges = json.entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges.splice(0, 8)
const photos = edges.map(({ node }) => {
return {
url: `https://www.instagram.com/p/${node.shortcode}/`,
thumbnailUrl: node.thumbnail_src,
displayUrl: node.display_url,
caption: node.edge_media_to_caption.edges[0].node.text
}
})
return photos
}
(async () => {
try {
const photos = await
fetchInstagramPhotos('https://www.instagram.com/hk.hairstyling/')
const container = document.getElementById('instagram-photos')
photos.forEach(el => {
const a = document.createElement('a')
const img = document.createElement('img')
a.setAttribute('href', el.url)
a.setAttribute('target', '_blank')
a.setAttribute('rel', 'noopener noreferrer')
a.classList.add('instagram-photo')
img.setAttribute('src', el.thumbnailUrl)
img.setAttribute('alt', el.caption)
a.appendChild(img)
container.appendChild(a)
})
} catch (e) {
console.error('Fetching Instagram photos failed', e)
}
})()

How to pass multiple arguments to one function?

I'm working on a project for school, and i'm trying to use 2 parameters in a function, but they are from 2 different functions. I have no clue how i can use them both.
What i'm trying to do is to actually use the code in showCityInfo in the function handleClickImg, but in order to do that i need the data 'city'
which is passed onto showCityInfo from the function getCityInfo, where the data is collected from my php.
So in short, i want to use the data 'city' and 'marker(=e.currentTarget)' in a function to do the following code i put in bold
{
const init = () => {
let radiobutton = document.querySelectorAll('.radio_button');
radiobutton.forEach(r => {
r.addEventListener("change", changeOpacity);
let $heart = document.querySelectorAll('.sidebar > svg');
$heart.forEach(h => {
h.addEventListener('click', changeColor);
})
document.documentElement.classList.add('has-js');
const $input = document.querySelector(`.world_form`);
console.log($input);
if ($input) {
$input.addEventListener(`change`, handleChangeFilter);
}
});
$markers = document.querySelectorAll('.world_map > img');
console.log($markers);
$markers.forEach(marker => {
marker.addEventListener('click', handleClickImg);
})
}
const handleChangeFilter = e => {
const alignment = e.target.value;
console.log(alignment);
const path = window.location.href.split(`?`)[0];
const qs = `?alignment=${alignment}`;
getCityInfo(`${path}${qs}`);
};
const getCityInfo = async url => {
console.log(url);
const response = await fetch(url, {
headers: new Headers({
Accept: 'application/json'
})
});
const city = await response.json();
console.log(city);
window.history.pushState({}, ``, url);
showCityInfo(city);
};
const showCityInfo = city => { **
const $parent = document.querySelector(`.contact_wrapper`);
$parent.innerHTML = ``;
$parent.innerHTML += `<p class="contact_info"><span>email:</span> Carvee${city.name}#hotmail.com</p>
<p class="contact_info"><span>tel:</span> ${city.tel} 476 03 51 07</p>` **
};
const handleClickImg = e => {
marker = e.currentTarget;
console.log(marker);
if (marker.id == city.city_code) {
}
}
In case you only have to compare a city and a marker at a time, I think what you should do is declare two global variables outside of the functions to store the city and marker data and be able to access and compare them anywhere.
//...
let city, marker;
const getCityInfo = async url => {
console.log(url);
const response = await fetch(url, {
headers: new Headers({
Accept: 'application/json'
})
});
city = await response.json();
console.log(city);
window.history.pushState({}, ``, url);
showCityInfo();
};
const showCityInfo = () => {
const $parent = document.querySelector(`.contact_wrapper`);
$parent.innerHTML = ``;
$parent.innerHTML += `<p class="contact_info"><span>email:</span> Carvee${city.name}#hotmail.com</p><p class="contact_info"><span>tel:</span> ${city.tel} 476 03 51 07</p>`
};
const handleClickImg = e => {
marker = e.currentTarget;
console.log(marker);
if (marker.id == city.city_code) {
}
}

Node.js Call a method after another method is completed

I would like to call my "app.get('/news/news-desc', (req, res)" method after "app.get('/news/api/:newsName', function(req, res)" is completed.
Here is my code:
let articleUrlArray = [];
app.get('/news/api/:newsName', function(req, res) {
const API_KEY = 'example';
let data = '';
const techCrunchURL = `https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${API_KEY}`
switch(req.params.newsName) {
case 'tech-crunch':
request(techCrunchURL, function(err, response, html) {
let formattedData = JSON.parse(response.body);
for(let i = 0; i < formattedData.articles.length; i++) {
articleUrlArray.push(formattedData.articles[i].url);
}
data = response.body;
res.setHeader('Content-Type', 'application/json');
res.send(data);
});
break;
default:
data = 'Please type in correct news source';
break;
}
})
const checkBody = res => (err, response, html) => {
const $ = cheerio.load(html);
const articleContent = $('.article-content').children('p')
const bodyOne = articleContent.eq(0).text()
const bodyTwo = articleContent.eq(1).text()
const isExtensive = bodyOne.split(' ').length > 50
res(isExtensive ? { bodyOne } : { bodyOne, bodyTwo })
}
const getArticle = article => new Promise(res => request(article, checkBody(res)))
app.get('/news/news-desc', (req, res) => {
Promise.all(articleUrlArray.map(getArticle)).then(data => res.send(JSON.stringify(data)))
})
As you can see, the first method calls the "newsapi.org" and gets 10 articles. Then it would only extract the urls of those articles and push them into articleUrlArray.
After the urls have been pushed into the articleUrlArray, it would look like this:
let articleUrlArray = [ 'https://techcrunch.com/2018/05/19/shared-housing-startups-are-taking-off/',
'https://techcrunch.com/2018/05/19/shared-housing-startups-are-taking-off/',
'https://techcrunch.com/2018/05/19/my-data-request-lists-guides-to-get-data-about-you/',
'https://techcrunch.com/2018/05/19/siempos-new-app-will-break-your-smartphone-addiction/',
'https://techcrunch.com/2018/05/19/la-belle-vie-wants-to-compete-with-amazon-prime-now-in-paris/',
'https://techcrunch.com/2018/05/19/apple-started-paying-15-billion-european-tax-fine/',
'https://techcrunch.com/2018/05/19/original-content-dear-white-people/',
'https://techcrunch.com/2018/05/19/meet-the-judges-for-the-tc-startup-battlefield-europe-at-vivatech/',
'https://techcrunch.com/2018/05/18/nasas-newest-planet-hunting-satellite-takes-a-stellar-first-test-image/',
'https://techcrunch.com/video-article/turning-your-toys-into-robots-with-circuit-cubes/',
'https://techcrunch.com/2018/05/18/does-googles-duplex-violate-two-party-consent-laws/' ];
It would just be filled up with urls.
Then the second method, would use the filled up articleUrlArray to do its own thing.
However, currently for my code, the second method runs first before the articleUrlArray has been filled up.
I would like to run the second method after the first method completes and the articleUrlArray has been filled up with urls.
Could you please help me with this?
let articleUrlArray = [];
const addArticleUrl = url => articleUrlArray.push(url)
const checkBody = res => (err, response, html) => {
const $ = cheerio.load(html);
const articleContent = $('.article-content').children('p')
const bodyOne = articleContent.eq(0).text()
const bodyTwo = articleContent.eq(1).text()
const isExtensive = bodyOne.split(' ').length > 50
res(isExtensive ? { bodyOne } : { bodyOne, bodyTwo })
}
const getArticle = article => new Promise(res => request(article, checkBody(res)))
const newsDescMiddleware = app.get('/news/news-desc', (req, res) => {
Promise.all(articleUrlArray.map(getArticle)).then(data => res.send(JSON.stringify(data)))
})
const techCrunch = res => url => request(url, (err, response, html) => {
let formattedData = JSON.parse(response.body);
formattedData.articles.forEach(article => addArticleUrl(article.url))
res(response.body)
})
const getNewsByName = (newsName, url) => new Promise((res, reject) => ({
'tech-crunch': techCrunch(res)(url)
}[newsName])) || reject()
const getNewsByNameMiddleware = (req, res) => {
const API_KEY = 'example';
const techCrunchURL = `https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${API_KEY}`
getNewsByName(req.params.newsName, url)
.then(body => {
res.setHeader('Content-Type', 'application/json');
res.send(body)
})
.catch(() => res.send('Please type in correct news source'))
}
app.get('/news/api/:newsName', getNewsByNameMiddleware, newsDescMiddleware)
Here, I made you some middlewares.
I am assuming that you don't need the response of the previous middleware.
I like to split the code by its responsibilities and write it functionally.
You can separate the core logic of the first route to a function and re-use it in both places, if you please. however you still need to provide newsName parameter to GET '/news/news-desc' endpoint.
Example for your code.
let articleUrlArray = [];
function getNewsNames(newsName, callback) {
const API_KEY = 'example';
let data = '';
const techCrunchURL = `https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${API_KEY}`
switch (newsName) {
case 'tech-crunch':
request(techCrunchURL, function (err, response, html) {
let formattedData = JSON.parse(response.body);
for (let i = 0; i < formattedData.articles.length; i++) {
articleUrlArray.push(formattedData.articles[i].url);
}
data = response.body;
callback(null, data);
});
break;
default:
data = 'Please type in correct news source';
callback('Error', data);
break;
}
}
app.get('/news/api/:newsName', function (req, res) {
getNewsNames(req,params.newsName, (err, data) => {
if (!err) {
res.setHeader('Content-Type', 'application/json');
}
return res.send(data);
})
})
const checkBody = res => (err, response, html) => {
const $ = cheerio.load(html);
const articleContent = $('.article-content').children('p')
const bodyOne = articleContent.eq(0).text()
const bodyTwo = articleContent.eq(1).text()
const isExtensive = bodyOne.split(' ').length > 50
res(isExtensive ? { bodyOne } : { bodyOne, bodyTwo })
}
const getArticle = article => new Promise(res => request(article, checkBody(res)))
app.get('/news/news-desc/:newsName', (req, res) => {
getNewsNames(req.params.newsName, (err, data) => {
// by now, the articleUrlArray array will be filled
Promise.all(articleUrlArray.map(getArticle)).then(data => res.send(JSON.stringify(data)))
})
})

Creating list items after GET request is complete

I'm trying to figure out a more efficient away to create the list items in the DOM.
At the moment the list is created as each API request is made.
I'm pushing each object into its own Array, I would like to create the list once all the data has loaded.
Additionally i'm using Webpack and Babel.
let streamApi = 'https://wind-bow.glitch.me/twitch-api/streams/';
let twitchUsers = ['ESL_SC2', 'OgamingSC2', 'freecodecamp', 'noobs2ninjas', 'comster404'];
let streamByUser = [];
window.onload = function() {
//Make a API request for each user and store in an array
twitchUsers.map((user) => {
fetch(streamApi + user, {method: 'GET'})
.then(response => response.json())
.then(json => {
streamByUser.push(json);
let uL = document.getElementById("user-list");
let listItem = document.createElement("li");
listItem.className = "list-group-item";
if (json.stream === null) {
listItem.innerHTML = "null";
} else {
listItem.innerHTML = json.stream.channel.display_name;
}
uL.appendChild(listItem);
});
});
};
UPDATE:
All is working!
Not tested but I hope it should work as expected.
const streamApi = "https://wind-bow.glitch.me/twitch-api/streams/";
const twitchUsers = [
"ESL_SC2",
"OgamingSC2",
"freecodecamp",
"noobs2ninjas",
"comster404"
];
const twitchUsersStreams = twitchUsers.map(user =>
fetch(streamApi + user, { method: "GET" }).then(res => res.json())
);
let streamByUser = [];
window.onload = function() {
Promise
.all(twitchUsersStreams)
.then(everythingArray => {
//do something with everythingArray after all the requests resolved
})
.catch(err => {
// As soon as any of the 'fetch' results in promise rejection
});
};
I would probably do something like this because I really like to decompose a task into small functions that reduce the need for inline comments and keep mutable state to a minimum.
const streamApi = 'https://wind-bow.glitch.me/twitch-api/streams/';
const twitchUsers = ['ESL_SC2', 'OgamingSC2', 'freecodecamp', 'noobs2ninjas', 'comster404'];
window.onload = async function () {
const list = document.getElementById("user-list");
const addToList = list.appendChild.bind(list);
const twitchStreams = await fetchUsers(twitchUsers);
twitchStreams.map(toListItem).forEach(addToList);
};
async function fetchUser(user) {
const response = await fetch(`${streamApi}${user}`, {method: 'GET'});
return response.json();
}
function fetchUsers(users) {
return Promise.all(users.map(fetchUser));
}
function toListItem(user) {
const listItem = document.createElement("li");
listItem.className = "list-group-item";
listItem.innerHTML = user.stream !== null
? user.stream.channel.display_name
: "null";
return listItem;
}

Categories

Resources