Now that your Supabase project is set up and you have a basic users table, it's time to get some data into it and then retrieve it. This is where the magic of interacting with your database really begins. Supabase, by default, provides a JavaScript client library that makes these operations incredibly straightforward.
Let's start by inserting some sample data into our users table. We'll use the Supabase JavaScript client to perform this operation. Imagine you have a simple registration form where a new user signs up. You'd want to capture their email and a username, and maybe set a default created_at timestamp (though Supabase often handles this automatically if you've set it up correctly).
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY'
const supabase = createClient(supabaseUrl, supabaseAnonKey)
async function insertUser(email, username) {
const { data, error } = await supabase
.from('users')
.insert([
{ email: email, username: username },
])
if (error) {
console.error('Error inserting user:', error)
} else {
console.log('User inserted successfully:', data)
}
}
// Example usage:
// insertUser('jane.doe@example.com', 'janedoe')In the code above, we import the createClient function, initialize our Supabase client with your project's URL and anonymous key (remember to replace the placeholders with your actual credentials), and then define an insertUser async function. This function uses the .from('users') method to target our table and .insert() to add new rows. We pass an array of objects, where each object represents a row to be inserted. If the insertion is successful, data will contain the newly inserted row(s); otherwise, error will hold the details of any problem.
Now, let's move on to querying the data we've inserted. Retrieving information from your database is a fundamental operation. You might want to fetch all users, find a specific user by their ID, or filter users based on certain criteria.
Here's how you can select all users from the users table: