I’m building a site using sapper and requesting data from an API. It has been working smooth until now.
When I’m going from site.com/title/id1 to site.com/title/id2 the new information is not loaded until I hit a manual refresh. Any ideas?
import { stores, goto } from "#sapper/app";
import Card from "../_titlecard.svelte";
const { page } = stores();
const { slug } = $page.params;
import { onMount } from "svelte";
let looper = [];
let artistName = "";
let titleName = "";
let dvdCover = "";
let titleCover = "";
let genre = "";
let tracks = [];
onMount(async () => {
const res = await fetch(`https://.com/api/title/${slug}`);
const data = await res.json();
artistName = data.artistName;
titleName = data.name;
dvdCover = data.graphics.dvd;
titleCover = data.graphics.landscape;
genre = data.genre;
tracks = data.tracks.length;
const res2 = await fetch(`https://.com/api/artists/all`);
const data2 = await res2.json();
let moreTitles = [];
const more = data2.map((x) => {
if (x.titles.length > 0 && x.genre === genre) {
looper.push(x.titles[0]);
looper = moreTitles;
}
});
});
And then I have this in the html
{#each looper.slice(0, 4) as item, i}
<Card imgurl={item.graphics.dvd} concert={item.name} id={item.id} />
{/each}
A page component is not unmounted and mounted again if the navigation results in the same page component being used, so your onMount will only be run once with the first id.
You could use a reactive statement to make sure you run the desired code every time $page.params.slug changes.
Example
import { stores, goto } from "#sapper/app";
import Card from "../_titlecard.svelte";
const { page } = stores();
let looper = [];
let artistName = "";
let titleName = "";
let dvdCover = "";
let titleCover = "";
let genre = "";
let tracks = [];
$: (async () => {
const { slug } = $page.params;
const res = await fetch(`https://.com/api/title/${slug}`);
const data = await res.json();
artistName = data.artistName;
titleName = data.name;
dvdCover = data.graphics.dvd;
titleCover = data.graphics.landscape;
genre = data.genre;
tracks = data.tracks.length;
const res2 = await fetch(`https://.com/api/artists/all`);
const data2 = await res2.json();
let moreTitles = [];
data2.forEach((x) => {
if (x.titles.length > 0 && x.genre === genre) {
moreTitles.push(x.titles[0]);
}
});
looper = moreTitles;
})();
Related
I'm doing an operation inside my function and I want to store my JSON data with AsyncStorage and use it elsewhere, but I'm getting an error in react native
this is my code block;
onPress={() => {
press = item.id;
// console.warn(press);
ars = options;
dd = JSON.stringify(ars);
cc = JSON.parse(dd);
for (var i = 0; i < cc.length; i++) {
if (cc[i].id == press) {
// console.warn(cc[i]);
var productData = cc[i];
var stri = JSON.stringify(cc[i]);
AsyncStorage.setItem('ProductData', stri);
var abc = AsyncStorage.getItem('ProductData');
console.warn(stri);
console.warn(abc);
}
}
}}>
how can i solve that problem?
thanks.
var abc = await AsyncStorage.getItem('ProductData');
add await as it is promise that all
so whole code will look like this
onPress={async () => {
press = item.id;
// console.warn(press);
ars = options;
dd = JSON.stringify(ars);
cc = JSON.parse(dd);
for (var i = 0; i < cc.length; i++) {
if (cc[i].id == press) {
// console.warn(cc[i]);
var productData = cc[i];
var stri = JSON.stringify(cc[i]);
AsyncStorage.setItem('ProductData', stri);
var abc =await AsyncStorage.getItem('ProductData');
console.warn(stri);
console.warn(abc);
}
}
}}>
add async to function and add await
I'm trying to implement server side pagination with NodeJS/Express. But the frontend rendering of it isn't working as expected. I fetch from a third-party API and implement the logic for the pagination. I then connect it to the frontend for rendering.
I have created cards to render the information from the API, first time remove the cards to render next page elements/cards with the code:
if(card !== undefined){
card.remove();
}
It works and it removes the cards, you can see this in the frontend, first eventlistener. But when I try to implement the same in the second eventlistener the elements/cards aren't removed and replaced with new ones.
Pagination - Backend
const express = require('express');
const router = express.Router();
const fetch = require('node-fetch');
router.get('/pokemon', function(req, res) {
async function getPokemonInfo(){
return fetch('https://pokeapi.co/api/v2/pokemon?limit=251')
.then(response => response.json())
.then(data => {
getDetailsPokemon(data)
}).catch(error => {
console.log(error);
})
}
getPokemonInfo()
async function getDetailsPokemon(pokemon){
const pokemonArr = pokemon.results;
const eachPokemon = pokemonArr.map(pokeEl => {
return fetch(pokeEl.url)
.then(response => response.json())
.catch(error => {
console.log(error);
})
})
Promise.all(eachPokemon)
.then(values => {
const page = parseInt(req.query.page);
const limit = parseInt(req.query.limit);
console.log(page, limit);
const startIndex = (page - 1) * limit;
const endIndex = page * limit;
console.log(startIndex, endIndex);
const results = {}
if(endIndex < values.length){
results.next = {
page: page + 1,
limit: limit
}
}
if(startIndex > 0){
results.previous = {
page: page - 1,
limit: limit
}
}
results.result = values.slice(startIndex, endIndex);
console.log(results);
res.json(results)
})
}
})
module.exports = router;
Pagination - Frontend
const paginatedApp = {
paginatedPokemon: async function(){
await fetch(`http://localhost:1337/pokemon?page=1&limit=20`)
.then(response => response.json())
.then(data => {
this.createCards(data)
})
},
createCards: function(pokemonObj){
let next = document.querySelector('.next');
let previous = document.querySelector('.previous');
pokemonObj.result.map(pokeEl => {
// Variables
let main = document.querySelector('main');
let card = document.createElement('div');
let imgHolder = document.createElement('div');
let img = document.createElement('img');
let infoHolder = document.createElement('div');
let infoBoxOne = document.createElement('div');
let infoBoxTwo = document.createElement('div');
let pId = document.createElement('p');
let pName = document.createElement('p');
let boxForType = document.createElement('div');
let id = document.createTextNode('id:');
let name = document.createTextNode('name:');
let type = document.createTextNode('type:');
// Info box 1
let infoPId = document.createElement('p');
let infoPName = document.createElement('p');
let infoPType = document.createElement('p');
infoPId.append(id);
infoPName.append(name);
infoPType.append(type);
infoBoxOne.append(infoPId, infoPName, infoPType);
infoBoxTwo.append(pId, pName, boxForType);
// Lägg till klasser
card.classList.add('card');
imgHolder.classList.add('imgHolder');
infoHolder.classList.add('infoHolder');
boxForType.classList.add('boxForType');
img.classList.add('img');
infoHolder.classList.add('infoHolder');
pId.classList.add('id');
pName.classList.add('name');
infoBoxOne.classList.add('infoBoxOne');
infoBoxTwo.classList.add('infoBoxTwo');
img.src = pokeEl.sprites.other['official-artwork']['front_default'];
pId.append(`#${pokeEl.id}`);
pName.append(pokeEl.name);
// Types
pokeEl.types.map(pokeType => {
let pokemonType = pokeType.type.name
let pokes = document.createElement('p');
pokes.append(pokemonType)
boxForType.append(pokes);
})
imgHolder.appendChild(img);
card.appendChild(imgHolder)
main.appendChild(card);
infoHolder.append(infoBoxOne)
infoHolder.append(infoBoxTwo)
card.appendChild(infoHolder);
boxForType.children[0].style.border = '1px solid #fff';
boxForType.children[1] ? boxForType.children[1].style.border = '1px solid #fff' : console.log('boxForType.children[1] dosen\'t exist for this post');
next.addEventListener('click', () => {
if(card !== undefined){
card.remove();
}
})
})
// Second next eventlistener
next.addEventListener('click', () => {
fetch(`http://localhost:1337/pokemon?page=${pokemonObj.next.page++}&limit=20`)
.then(response => response.json())
.then(data => {
data.result.map(dataEl => {
let main = document.querySelector('main');
let card = document.createElement('div');
if(card !== undefined){
card.remove();
}
let imgHolder = document.createElement('div');
let img = document.createElement('img');
let infoHolder = document.createElement('div');
let infoBoxOne = document.createElement('div');
let infoBoxTwo = document.createElement('div');
let pId = document.createElement('p');
let pName = document.createElement('p');
let boxForType = document.createElement('div');
let id = document.createTextNode('id:');
let name = document.createTextNode('name:');
let type = document.createTextNode('type:');
// Info box 1
let infoPId = document.createElement('p');
let infoPName = document.createElement('p');
let infoPType = document.createElement('p');
infoPId.append(id);
infoPName.append(name);
infoPType.append(type);
infoBoxOne.append(infoPId, infoPName, infoPType);
infoBoxTwo.append(pId, pName, boxForType);
// Lägg till klasser
card.classList.add('card');
imgHolder.classList.add('imgHolder');
infoHolder.classList.add('infoHolder');
boxForType.classList.add('boxForType');
img.classList.add('img');
infoHolder.classList.add('infoHolder');
pId.classList.add('id');
pName.classList.add('name');
infoBoxOne.classList.add('infoBoxOne');
infoBoxTwo.classList.add('infoBoxTwo');
img.src = dataEl.sprites.other['official-artwork']['front_default'];
pId.append(`#${dataEl.id}`);
pName.append(dataEl.name);
// Types
dataEl.types.map(pokeType => {
let pokemonType = pokeType.type.name
let pokes = document.createElement('p');
pokes.append(pokemonType)
boxForType.append(pokes);
})
imgHolder.appendChild(img);
card.appendChild(imgHolder)
main.appendChild(card);
infoHolder.append(infoBoxOne)
infoHolder.append(infoBoxTwo)
card.appendChild(infoHolder);
if(card !== undefined){
card.remove();
}
})
})
})
}
}
paginatedApp.paginatedPokemon();
I'm having problem with loading from local storage.
Here's a part of the code
const getTerminus = () => {
let terminus;
if (localStorage.getItem("terminus") === null) {
terminus = [];
} else {
terminus = JSON.parse(localStorage.getItem("terminus"));
}
let directions;
if (localStorage.getItem("directions") === null) {
directions = [];
} else {
directions = JSON.parse(localStorage.getItem("directions"));
}
terminus.forEach(async(stop) => {
let API_URL =
"https://ckan.multimediagdansk.pl/dataset/c24aa637-3619-4dc2-a171-a23eec8f2172/resource/d3e96eb6-25ad-4d6c-8651-b1eb39155945/download/stopsingdansk.json";
let response = await fetch(API_URL);
let data = await response.json();
const {
stops,
stopId,
stopName,
stopCode,
zoneId
} = data;
let input = stop;
let ID;
let dataArr = [];
for (let i = 0; i < stops.length; i++) {
if (
stops[i].stopName === input &&
stops[i].stopCode === directions[terminus.indexOf(input)] &&
stops[i].zoneId === 1
) {
ID = stops[i].stopId;
dataArr = [ID, stops[i].stopName];
}
}
API_URL = `https://ckan2.multimediagdansk.pl/delays?stopId=${ID}`;
response = await fetch(API_URL);
data = await response.json();
const {
delay,
estimatedTime,
routeId,
headsign
} = data;
let times = [];
let routeIds = [];
let headsigns = [];
for (let i = 0; i < delay.length; i++) {
times.push(delay[i].estimatedTime);
routeIds.push(delay[i].routeId);
headsigns.push(delay[i].headsign);
}
routeIds.push(" ");
times.push(" ");
const cardDiv = document.createElement("div");
cardDiv.classList.add("card");
const stopNameDiv = document.createElement("div");
stopNameDiv.classList.add("stop-name-div");
cardDiv.appendChild(stopNameDiv);
const stopNameSpan = document.createElement("span");
stopNameSpan.innerText = dataArr[1];
stopNameSpan.classList.add("stop-name-span");
stopNameDiv.appendChild(stopNameSpan);
const scheduleDiv = document.createElement("div");
scheduleDiv.classList.add("schedule-div");
cardDiv.appendChild(scheduleDiv);
if (headsigns.length !== 0) {
routeIds.unshift("Line");
headsigns.unshift("Direction");
times.unshift("Departure");
}
const lineSpan = document.createElement("span");
lineSpan.innerText = routeIds.join("\n");
lineSpan.classList.add("line-span");
scheduleDiv.appendChild(lineSpan);
const dirSpan = document.createElement("span");
dirSpan.innerText = headsigns.join("\n");
dirSpan.classList.add("dir-span");
scheduleDiv.appendChild(dirSpan);
const timeSpan = document.createElement("span");
timeSpan.innerText = times.join("\n");
timeSpan.classList.add("time-span");
scheduleDiv.appendChild(timeSpan);
const buttonsDiv = document.createElement("div");
buttonsDiv.classList.add("buttons-div");
cardDiv.appendChild(buttonsDiv);
const deleteButton = document.createElement("button");
deleteButton.innerHTML = '<i class="fas fa-trash"></i>';
deleteButton.classList.add("delete-button");
buttonsDiv.appendChild(deleteButton);
const dirButton = document.createElement("button");
dirButton.innerHTML = '<i class="fas fa-retweet"></i>';
dirButton.classList.add("reverse-button");
buttonsDiv.appendChild(dirButton);
stopList.appendChild(cardDiv);
});
};
document.addEventListener("DOMContentLoaded", getTerminus);
Terminus contains stop names, and directions contains direction codes.
On refresh, it fetches data from API based on stop name and direction, and displays a card with departure time etc.
The problem is, on closing and re-opening the page cards are sometimes displayed in a wrong order. I have found out, that as time between closing and opening lengthens, the probability of this occurring gets higher. After simple refresh everything is in correct order.
Does it have something to do with browser cache? Has anyone had similar issue or knows what's going on?
Alright, as #Yoshi stated, it was insequential promise error. I managed to fix it by using reduce().
Here are the threads that helped me
Resolve promises one after another (i.e. in sequence)?
Why Using reduce() to Sequentially Resolve Promises Works
The logic seems sound but my ul is not displaying what I am asking it to. I have used console.logs and I am for sure getting poem in the function displayPoem(poem) but it isn't showing up when I button click. Any help would be greatly appreciated!
const inputsList = document.querySelector('ol');
const poemsList = document.getElementById('savedThoughts');
const form = document.getElementById('')
const submitButton = document.getElementById('submitThoughts');
const startButton = document.querySelector('#startButton')
startButton.onclick = () => {
const ranNum = generateRanNum();
generateInputs(ranNum)
changeToRestartText()
}
submitButton.onclick = () => {
const poem = savePoem();
console.log(poem)
displayPoem(poem);
clearForm()
}
const generateRanNum = () => {
let randomNumber = Math.floor(Math.random() * 20);
return randomNumber
}
const changeToRestartText = () => {
startButton.textContent = 'Restart Game'
}
const generateInputs = (ranNum) => {
const listItem = document.createElement('li');
for(let i = 1; i <= ranNum; i++){
const input = document.createElement('input');
listItem.appendChild(input).setAttribute('type', 'text');
console.log(ranNum)
}
inputsList.appendChild(listItem);
}
const savePoem = () => {
let poemArr = [];
const input = document.querySelectorAll('input');
input.forEach(element => {
poemArr.push(element.value);
})
// console.log(poemArr)
return poemArr;
}
const displayPoem = (poem) => {
const savedPoem = document.createElement('li')
const savedText = document.createElement('span')
const deletePoem = document.createElement('button')
console.log(poem)
savedPoem.appendChild(savedText);
savedText.textContent = poem.toString();
savedPoem.appendChild(deletePoem);
deletePoem.textContent = 'Delete';
poemsList.appendChild(savedPoem)
deletePoem.onclick = e => {
poemsList.removeChild(savedPoem);
}
}
const clearForm = () => {
const inputLi = document.querySelectorAll('li');
inputLi.forEach(element => {
element.remove()
})
}
small html segment
<div >
<ul id="savedThoughts">
</ul>
</div>
Your saved list items aren't showing up because your submit onclick calls displayPoem which creates list items and then calls clearForm which removes all list items on the page. Try inputLi = document.querySelectorAll('ol > li').
I have written a program to extract links to download photos in three steps:
The getPersons() function get the complete list of people to traverse.
Get the photos download links from the list of persons.
Download from the list created in step 2.
I am trying to refactor step 2 into an async function.
Is there an easy way to refactor second step into a function to make the code more readable?
Ideally, I would like to retrieve all the links and only then, start the download.
const axios = require("axios");
const cheerio = require("cheerio");
const url = "https://www.website.com";
const persons = [];
async function getPersons() {
await axios.get(url).then(response => {
const html = response.data;
const $ = cheerio.load(html);
const personList = $(".bio-btn");
console.log(personList.length);
personList.each(function() {
const link_raw = $(this).attr("href");
const link = url + link_raw;
const name = link_raw.replace("/bio/", "");
person.push({
name,
link
});
});
});
}
getPersons().then(function() {
persons.forEach(async function(person) {
var personLink = person.link;
await axios.get(personLink).then(response => {
const html = response.data;
const $ = cheerio.load(html);
const snapshots = $(".ratio-4-3");
snapshots.each(function() {
const pic = $(this).attr("style");
if (pic != undefined && pic.includes("biopicture")) {
var bioPhoto = s[1];
}
});
});
});
});
You are hardly getting much benefit out of your asynchronicity, as you end up making serial requests. I'd write it this way (untested):
async function getPersons() {
const response = await axios.get(url);
const html = response.data;
const $ = cheerio.load(html);
const personList = $('.bio-btn');
const persons = [];
personList.each(function() {
const link_raw = $(this).attr('href');
const link = url + link_raw;
const name = link_raw.replace("/bio/", "");
persons.push({
name,
link,
});
});
return persons;
};
async function getSnapshots() {
const persons = await getPersons();
const linkPromises = persons.map(person => axios.get(person.link));
const linkResponses = await Promise.all(linkPromises);
linkResults.forEach(response => {
const html = response.data;
const $ = cheerio.load(html);
const snapshots = $(".ratio-4-3");
// ...
});
}
I would refactor it like this. Removing .then() methods and the function keyword on anonymous functions makes the code look cleaner.
Using Promise.all() enables you to start all the downloads asynchronously which could be better than downloading images one by one.
const axios = require('axios');
const cheerio = require('cheerio');
const url = 'https://www.website.com';
async function getPersons() {
const response = await axios.get(url);
return extractPersonList(response);
}
// Step 1
function extractPersonList(response) {
const persons = [];
const html = response.data;
const $ = cheerio.load(html);
const personList = $('.bio-btn');
console.log(personList.length);
personList.each(() => {
const link_raw = $(this).attr('href');
const link = url + link_raw;
const name = link_raw.replace('/bio/', '');
persons.push({
name,
link
});
});
return persons;
}
async function getPhotos() {
const persons = await getPersons();
const promisies = persons.map(p => axios.get(p.link));
// Step 2
const responses = await Promise.all(promisies);
// Step 3
responses.forEach(response => {
const html = response.data;
const $ = cheerio.load(html);
const snapshots = $('.ratio-4-3');
snapshots.each(() => {
const pic = $(this).attr('style');
if (pic && pic.includes('biopicture')) {
var bioPhoto = s[1];
}
});
});
}
// Call getPhotos to start the process
getPhotos();