3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Supabaseで取得したデータの表示順序を保持する方法

Posted at

はじめに

学習記録の一覧テーブルのデータを更新した際、更新したデータがテーブル一覧の最後に表示されてしまうという現象が発生しました。

そこで今回は、データの順番を変更せずに更新できるようにする方法について紹介します。

データ更新ソート問題.gif

データ構造
export class Record {
    constructor(
        public id: number,
        public title: string,
        public time: number,
        public created_at: string 
    ) {}
}
study-record.ts
//データ取得
export async function GetAllRecords(): Promise<Record[]> {
    const response = await supabase.from("study-record").select("*")

    if (response.error) {
        throw new Error(response.error.message)
    }
    const recordsData = response.data.map((record) => {
        return new Record(record.id,record.title,record.time,record.created_at)
    })
    return recordsData
}


解決法

データ取得時にソート条件を指定することで、順番を保ったまま表示できました。
以下のように、created_at(作成日時)で昇順に並べるように .order() を追加しました。

//データ取得
export async function GetAllRecords(): Promise<Record[]> {
    const response = await supabase
                        .from("study-record")
                        .select("*")
                        // 作成日時の古い順にする
                        .order("created_at", { ascending: true})

    if (response.error) {
        throw new Error(response.error.message)
    }
    const recordsData = response.data.map((record) => {
        return new Record(record.id,record.title,record.time,record.created_at)
    })
    return recordsData
}

.order("created_at", { ascending: true}) の部分が重要で、これによりcreated_atフィールドの値で古い順(昇順)にソートしています。

おわりに

今回は、データを更新した際に順番が変わってしまう問題に対して、ソート処理を追加することで解決する方法を学びました。
Supabaseでは、.order() を使うことで簡単に並び順を制御できることがわかり、Supabaseに対する理解が深まりました。

参考

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?