I have a page that gets a list of posts from Supabase and displays them.
I want to listen out for any changes in the database so that the display updates when someone creates a new post.
Currently, when a user adds a new post an item gets added to the list of data, but it displays the content of one of the other posts instead of the data the user has just entered. When you refresh the page, the correct data is shown:
Creating a post
Content duplicates one of the other pieces of data
Here’s the code so far:
feed.vue
<script setup>
definePageMeta({
pageTransition: {
name: "slide",
mode: "out-in",
},
layout: "feed",
});
const supabase = useSupabaseClient();
let testingChannel = null;
const allPosts = ref([]);
const getPosts = async () => {
console.log("GETTING POSTS");
const { data } = await supabase
.from("posts")
.select(`*,profiles(*)`)
.is("parent", null)
.order("created_at", { ascending: false });
allPosts.value = data;
};
await getPosts();
onMounted(() => {
testingChannel = supabase
.channel("testingChannel")
.on(
"postgres_changes",
{ event: "*", schema: "public", table: "posts" },
(payload) => {
console.log("Change received!", payload);
getPosts();
}
)
.subscribe();
});
onUnmounted(() => {
supabase.removeChannel(testingChannel);
});
</script>
<template>
<div class="m-6 pb-8">
<Card class="mb-6 p-4">
<FeedAddPost />
</Card>
<ul>
<li v-for="(post, i) in allPosts" :key="`post${i}`">
<FeedPost :post="post" />
</li>
</ul>
</div>
</template>
No matter what I do I can’t seem to get the page to update with the correct data straight after the user has submitted a post.
The strange thing is I’m using this code elsewhere on the site to update things on the fly and it’s working fine!
I’ve tried putting the data into a ref variable, using useAsyncData with refresh and anything else I can think of but the same issue keeps cropping up.