はじめに
学習記録の一覧テーブルのデータを更新した際、更新したデータがテーブル一覧の最後に表示されてしまうという現象が発生しました。
そこで今回は、データの順番を変更せずに更新できるようにする方法について紹介します。
データ構造
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に対する理解が深まりました。
参考