Search code examples
javascriptpostgresqlsupabase

Supabase puts certain rows at the top


My Supabase JS client performs an INSERT on the messages table using the following.

import { createClient } from "@supabase/supabase-js";

const supabase = createClient(
    "MY SUPABASE URL",
    "MY ANON KEY"
);

async function insertMessage(sender, content, file, parent) {
    return await supabase.from("messages").insert({
        id: uuidv4(),
        date: Date.now(),
        sender: sender,
        content: content || null,
        file: file || null,
        parent: parent,
    });
}

I have some old messages in the table from previous work, but as you can see below, the new entries are being inserted "above" the older messages, but still "below" one another. demo

My expectation would be that each new entry would be written at the bottom of the table always, so I'm trying to understand why is this. And how do I prevent it?

I haven't been able to find anything about this. Nobody else seems to have had the issue.


Solution

  • The comment by @Belayer led me to find a solution by adding .order("date") to my getMessages query. I changed getMessages to resemble the following

    async function getMessages(parent, fromIdx, maxResults) {
        return await supabase
            .from("messages")
            .select("*, users(avatarBase64, name)")
            .eq("parent", parent)
            .range(fromIdx, fromIdx + maxResults)
            .order("date"); // added this line
    }
    

    insertMessages didn't change

    async function insertMessage(sender, content, file, parent) {
        return await supabase.from("messages").insert({
            id: uuidv4(),
            date: Date.now(),
            sender: sender,
            content: content || null,
            file: file || null,
            parent: parent,
        });
    }