INSERT into the table and return id of the record Supabase JS

2 min read 05-10-2024
INSERT into the table and return id of the record Supabase JS


Inserting Data and Retrieving IDs with Supabase.js

Supabase provides a powerful and intuitive way to interact with your PostgreSQL database. One common task is inserting new data and retrieving the newly generated ID of the inserted record. This article will guide you through the process using the Supabase.js library.

The Problem

You want to add a new entry to a table in your Supabase database and need the unique ID of the newly created record. This ID is often required for subsequent operations or for referencing the record in other parts of your application.

The Solution

Supabase.js offers the insert method, which allows you to insert data into a table. To retrieve the ID, you can use the returning option and specify the desired columns.

Code Example

import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'your-supabase-url'; // Replace with your Supabase URL
const supabaseKey = 'your-supabase-key'; // Replace with your Supabase API Key

const supabase = createClient(supabaseUrl, supabaseKey);

async function insertData() {
  const { data: insertedData, error } = await supabase
    .from('your_table_name')
    .insert([
      {
        column1: 'value1',
        column2: 'value2',
        // ... other columns and their values
      },
    ])
    .returning('id'); // Specify the 'id' column

  if (error) {
    console.error(error);
    return;
  }

  console.log('Inserted data:', insertedData);
  console.log('Newly generated ID:', insertedData[0].id); 
}

insertData(); 

Explanation:

  1. Initialization: Create a Supabase client with your Supabase URL and API key.
  2. Insert Data: Use the insert method to add a new row to your table. Specify the table name (your_table_name) and an array of objects containing the data for each column.
  3. Returning ID: Utilize the returning option with the id column name to fetch the newly generated ID.
  4. Error Handling: Check for errors and display an error message if necessary.
  5. Accessing ID: The insertedData variable will contain an array of objects. In this case, it will have a single object with the id property containing the generated ID.

Unique Insights

  • Multiple Rows: You can insert multiple rows at once by passing an array of objects to the insert method.
  • Other Returning Columns: The returning option can be used to retrieve other columns from the inserted record.
  • Auto-Incrementing IDs: If your table uses a standard SERIAL or BIGSERIAL column for IDs, Supabase automatically manages the incrementing sequence.

Conclusion

This guide showcases how to effortlessly insert data into your Supabase database and retrieve the newly generated ID using Supabase.js. With a clear understanding of the insert method and the returning option, you can streamline data management in your application.

Resources