0

I am working on a small project to learn Supabase and NextJS. I am trying to add a JSON object to my sites array which is defined as a JSON array. I want to add the config (and more in the future) to the sites column based on the user's id that I get back from auth().

users table

This is what I could come up with but I keep getting this error: message: expected JSON array. I've tried wrapping the object with brackets to create an array and that doesn't work either.

const { data, error } = await supabase
  .from("users")
  .insert({
    sites: {...}) // config object
  .eq("id", user?.id);

I've tried different Filters per Supabase docs and nothing is working. There doesn't seem to be a clear way to update arrays with JSON from what I've searched, but I'm also very new to PostgreSQL databases.

4
  • 1
    "which is defined as a JSON array" - don't use json[]. Make it json, then store an array value.
    – Bergi
    Commented Apr 18, 2024 at 15:43
  • so are you saying for my insert go from this: .insert({sites: {...}) to this => .insert([sites: {...}]) ? Commented Apr 18, 2024 at 16:03
  • Also, when trying the to do that I get message: null value in column "id" of relation "users" violates not-null constraint Commented Apr 18, 2024 at 16:04
  • No. .insert({sites: {...}}) (or rather .insert({sites: [{...}]})) is fine, but you should change the column type in the database.
    – Bergi
    Commented Apr 18, 2024 at 20:15

1 Answer 1

0

I was able to solve with the following:

const { data, error } = await supabase
  .from("users")
  .update({
    sites: [
      ...stateUser.sites, // previous JSON objects
      testConfig(timestampWithTimeZone, stateUser?.sites), // new JSON object
    ],
  })
  .eq("id", stateUser?.id)
  .select();

Hope this will help someone else in the future!

1
  • What is stateUser variable? Did you fetch the user before updating? Commented Apr 11 at 20:34

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.