2

I am using supabase-js and have a table like this:

userID: string
timesVisited: number
eventName: string

I am using update like this:

Admin.from(tableName).update([{userID,eventName,timesVisited}])

Currently I have to make two calls one to get current timesViewed and then update it I was interested in knowing if there's a way I could directly increment the value instead of making 2 calls?

Shivam Sahil
  • 4,055
  • 3
  • 31
  • 62

1 Answers1

3

You would do this using a Postgres function and the .rpc method of the supabase-js library.

Create a function using the SQL editor

create function increment (x int, row_id int) 
returns void as
$$
  update table_name 
  set column_name = column_name + x
  where id = row_id
$$ 
language sql volatile;

And call it like:

const { data, error } = await supabase
  .rpc('increment', { x: 1, row_id: 2 })
Andrew Smith
  • 1,224
  • 6
  • 9
  • 1
    This is just an increment function, however I want to increment as well as update other fields – Shivam Sahil May 14 '23 at 05:40
  • 1
    Please read the function body, it increments and update the column. You can modify the function so it fits your use case better. In essence this is to show you that you can create functions and call them via the `.rpc` method if the normal supabase-js methods don't support that feature. – Andrew Smith May 14 '23 at 23:05