1
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?

【Next.js】supabase upsertしても更新されない挙動の解決方法(必須項目入れる or update使用)

Posted at

はじめに

 取得した値を使用してsupabaseのDBを更新しようと実装しましたが、期待した挙動になりませんでした。
こちら、解決方法について共有させていただきます。
 そもそもupsertの挙動について理解が不十分でした。
例えば下記のように記述していました。

.tsx
const { error: upsertError } = await supabase
 .from("users")
  .upsert({
    id: session_id,
    age: age,
    hobby: hobby,
  })
  .eq("id", session_id);

そもそもupsertとは

 データが存在するなら更新し、無ければ新規作成する操作。
今回のusersテーブルには他にnot-nullのnameカラムが存在していました。
upsertは一部のカラムの値だけの更新を狙う場合には向いておらず、eqも無視されてしまいます。

解決方法

 入力必須のカラムに値を入れるまたはupdateを使う。

.tsx
const { error: upsertError } = await supabase
 .from("users")
  .upsert({
    id: session_id,
    name: name,
    age: age,
    hobby: hobby,
  });
.tsx
const { error: upsertError } = await supabase
 .from("users")
  .update({
    id: session_id,
    age: age,
    hobby: hobby,
  }).
  eq("id", session_id);

参考

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!
▼▼▼

1
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
1
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?