2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】Supabaseのテーブルのデータを削除する

Posted at

はじめに

簡単な学習記録アプリを作成しています。
登録した学習記録に削除ボタンを付与し、ボタンを押すとその記録が見た目からも、Supabaseのテーブル上のデータも削除されるような実装をしたいです。
しかし、以下の問題に直面したため問題点と解決策をまとめます。

問題

  • Supabaseに登録したデータが削除できない
  • 削除ボタンを押した際のコンソールを確認すると、該当の要素よりひとつ前の要素が表示される
  • 削除したいもののidとSupabaseのテーブルのidが一致せずデータが削除されない

修正前のコード

SupabaseFuction.js
export const deleteRecords = async (id) => {
  const records = await supabase.from("study-record").delete().match(id);
  return records.data;
};
App.js
  const onClickDelete = async (id) => {
    const newRecords = [...records];
    newRecords.splice(id, 1);
    setRecords(newRecords);
    deleteRecords(id);
  };

  return (
  <>
    <button onClick={() => onClickDelete(id)}>削除</button>
  </>
  );

解決方法

  • そもそもSupabaseで作成したテーブルのidがuuidになっていなかった
  • recordの中にあるidがonClickDeleteに渡せていなかった

修正前のコード

SupabaseFuction.js
export const deleteRecords = async (id) => {
  const records = await supabase.from("study-record").delete().match({ id });
  return records.data;
};
App.js
  const onClickDelete = async (id) => {
    const newRecords = [...records];
    newRecords.splice(id, 1);
    setRecords(newRecords);
    deleteRecords(id);
  };
  
  return (
  <>
    <button onClick={() => onClickDelete(record.id)}>削除</button>
  </>
  );

おわりに

idを渡したいことばかりに気を取られてidがどこにあるのかが抜けていました…。
今回はonClickDeleteconsole.log(record.id);を試すことで解決に辿り着くことができました。
どこの何の値を渡したいのか、どこでつまづいているかをデバッグで調べていくことが重要だと気付かされました。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?