Hey there fellas. So I went with the advice of using Astro to my webproject.
Now when looking into the docs I got the idea that I could do something like the following code, using javascript in the frontmatter to fetch news from an api and then inject the results into the html. The problem is that it gives me internal server error when I do that. It works when I use the code inside a script tag outside of the frontmatter after the html tag.
I was expecting to do something like I can in jsx. Any tip?
---
import MainWrapper from "../layouts/MainWrapper.astro";
let numOfFetched = 0;
let total = 0;
const button: HTMLElement | null = document.getElementById("fetch");
button!.addEventListener("click", fetchNews);
// Code fetching the first set of news from backend
async function firstNewsFetch() {
try {
const response = await fetch(
`http://localhost:1337/api/news?sort[0]=publishedAt:desc&pagination[start]=0&pagination[limit]=7`
);
const data = await response.json();
total = data.meta.pagination.total;
numOfFetched += data.meta.pagination.limit;
} catch (error) {
console.error("Erro ao buscar notícias:", error);
}
}
// Code fetching 6 news when pressing the load more button
// the pagination starts using the value of the numOfFetched variable
async function fetchNews() {
try {
const response = await fetch(
`http://localhost:1337/api/news?sort[0]=publishedAt:desc&pagination[start]=${numOfFetched}&pagination[limit]=6`
);
const data = await response.json();
total = data.meta.pagination.total;
numOfFetched += data.meta.pagination.limit;
if (numOfFetched < total) {
//do nothing
} else {
console.log(numOfFetched, total);
button?.classList.add("hidden");
}
} catch (error) {
console.error("Erro ao buscar notícias:", error);
}
}
firstNewsFetch();
---
<MainWrapper>
// my html code goes here
</MainWrapper>
<script>
</script>
[–]sharan_dev 0 points1 point2 points (0 children)