S
Supabase•3y ago
Arvalaan

Chain Supabase Insert(s)

Wondering if I can chain a Supabase insert, for example: Insert into table x Select newly inserted row Insert into table y with id of newly inserted row And if so, how would a JS function look like?
5 Replies
Arvalaan
ArvalaanOP•3y ago
I thought since Supabase is a promise I could chain a .finally to it but it appears that's not working Think I figured it out! 😄
await supabase
.from("timetable")
.insert(scheduleEntries)
.select()
.then((result) => {
console.log(result);
});
await supabase
.from("timetable")
.insert(scheduleEntries)
.select()
.then((result) => {
console.log(result);
});
This works
const { data, error } = await supabase
.from("timetable")
.insert(scheduleEntries)
.select()
.then((data) => {
console.log(data);
});
const { data, error } = await supabase
.from("timetable")
.insert(scheduleEntries)
.select()
.then((data) => {
console.log(data);
});
this was my first attempt and didn't work
garyaustin
garyaustin•3y ago
You can also use an rpc call so they are also run as a transaction so if either insert fails, they both fail. And you only have one API call overhead. You would use insert returning in sql to get the id for the first inserted row, to use in the next insert call. Otherwise a postgres google would find you the two insert code in SQL.
Arvalaan
ArvalaanOP•3y ago
Uff, I've not worked with those RPCs yet but will take that into consideration
garyaustin
garyaustin•3y ago
You can easily do with two calls in the client, you just need to handle error cases for each insert as appropriate. In particular if the 2nd insert fails do you need to delete the first insert or not.
Arvalaan
ArvalaanOP•3y ago
Yeah makes sense, thanks for helping out Gary!

Did you find this page helpful?