<button>Show posts</button>
<output></output>
import { fromEvent } from "https://cdn.skypack.dev/rxjs@7.3.0";
import { switchMap } from "https://cdn.skypack.dev/rxjs@7.3.0/operators";
import { fromFetch } from "https://cdn.skypack.dev/rxjs@7.3.0/fetch";
const output = document.querySelector("output");
const button = document.querySelector("button");
fromEvent(button, "click")
.pipe(switchMap(getAlbums))
.subscribe(render, (err) => console.error(err));
function getAlbums() {
const userId = Math.round(Math.random() * 10);
return fromFetch(
`https://jsonplaceholder.typicode.com/albums?userId=${userId}`
).pipe(switchMap((res) => res.json()));
}
function render(res) {
console.log(res);
output.innerHTML = "";
for (const post of res) {
const article = document.createElement("article");
const h1 = document.createElement("h1");
const p = document.createElement("p");
h1.textContent = post.title;
p.textContent = `id:${post.id} userId: ${post.userId}`;
article.appendChild(h1);
article.appendChild(p);
output.appendChild(article);
}
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.