body {
margin: 16px;
line-height: 1.5;
color: #212121;
font-family: sans-serif;
}
p {
margin: 0;
}
.posts {
margin: 0;
list-style: none;
padding: 24px;
}
.posts li:not(:last-child) {
margin-bottom: 16px;
}
.post-title {
margin-top: 0;
margin-bottom: 8px;
font-size: 20px;
font-weight: 700;
}
.post-title:first-letter {
text-transform: uppercase;
}
.post-body {
margin: 0;
}
const fetchPostsBtn = document.querySelector(".btn");
const postList = document.querySelector(".posts");
fetchPostsBtn.addEventListener("click", async () => {
try {
const posts = await fetchPosts();
renderPosts(posts);
} catch (error) {
console.log(error);
}
});
async function fetchPosts() {
const params = new URLSearchParams({
_limit: 5,
_page: 3
});
const response = await axios.get(
`https://jsonplaceholder.typicode.com/posts?${params}`
);
return response.data;
}
function renderPosts(posts) {
const markup = posts
.map(({ id, title, body, userId }) => {
return `<li>
<h2 class="post-title">${title.slice(0, 30)}</h2>
<p><b>Post id</b>: ${id}</p>
<p><b>Author id</b>: ${userId}</p>
<p class="post-body">${body}</p>
</li>`;
})
.join("");
postList.innerHTML = markup;
}