We need somewhere to create the HTML for our posts. In index.html:
<div id="posts-list"></div>
In js/posts.js:
loadPosts();
async function loadPosts() {
const postsContainer = document.querySelector("#posts-list");
postsContainer.innerHTML = "";
try {
const { data: posts, error } = await supabase
.from("posts")
.select("*")
.order("created_at", { ascending: false });
if (error) {
// handle error
}
if (!posts || posts.length === 0) {
// display message about no posts
return;
}
posts.forEach((post) => {
const postElement = createPostElement(post);
postsContainer.appendChild(postElement);
});
} catch (error) {}
}
function createPostElement(post) {
const heading = document.createElement("h3");
heading.textContent = post.title;
return heading;
}
Key Concepts
.select("*")fetches all columns from the posts table..order("created_at", { ascending: false })sorts posts by newest first.- RLS automatically filters to show only the current user’s posts.
- We’ve simplified the display to show only the post
titleas an<h3>element. - Again, always display error messages to users.
We can also call loadPosts(); after creating a new post. This will refresh the list. Another way to do this would be to make the table real-time, but we won’t cover that in this lesson.