/supabase-tutorials

How to use Supabase with React?

Learn to integrate Supabase with React using our step-by-step guide. Set up your account, perform CRUD operations, and enable real-time updates effortlessly.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to use Supabase with React?

 

Step 1: Set Up Supabase Account and Project

 

To get started with using Supabase, you'll first need to create an account and a new project.

  1. Go to the Supabase website and sign up for an account.
  2. Once you are logged in, click on "New Project" to create a new project.
  3. Fill out the necessary details such as the project name, organization, and choose a database password.
  4. Wait for the project setup to complete. After it's created, you'll have access to your unique Supabase URL and API Keys, which you will use in your React application.

 

Step 2: Initialize React Application

 

If you haven't already, you'll need to create a new React application. If you have node installed, you can quickly bootstrap a React app using Create React App.

npx create-react-app my-supabase-app
cd my-supabase-app

 

Step 3: Install Supabase Client Library

 

You need to install the Supabase JavaScript client library to interact with the Supabase backend from your React application.

npm install @supabase/supabase-js

 

Step 4: Set Up Supabase Client

 

Create a new file for setting up the Supabase client. You will initialize the Supabase client with your Supabase URL and API key.

Create a supabaseClient.js file:


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

const supabaseUrl = 'https://your-project-ref.supabase.co'; // replace with your Supabase project URL
const supabaseAnonKey = 'your-anon-key'; // replace with your Supabase anon key

export const supabase = createClient(supabaseUrl, supabaseAnonKey);

Replace 'your-project-ref' and 'your-anon-key' with the actual values from your Supabase dashboard.

 

Step 5: Fetch Data from Supabase

 

To interact with your Supabase database, you will use the Supabase client you set up earlier. Here's how you can fetch data from a table:

import React, { useEffect, useState } from 'react';
import { supabase } from './supabaseClient';

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  async function fetchData() {
    const { data, error } = await supabase.from('your_table_name').select('*');
    if (error) console.log('Error fetching data:', error);
    else setData(data);
  }

  return (
    <div className="App">
      <h1>Supabase Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default App;

Replace 'your_table_name' with the actual table name you want to fetch data from in your Supabase project.

 

Step 6: Insert Data into Supabase

 

To insert data into your Supabase table, you'll need to use the insert method. Here's an example of how you can implement it:


async function insertData() {
  const { data, error } = await supabase
    .from('your_table_name')
    .insert([
      { column_name: 'value', other_column: 'other\_value' }
    ]);

  if (error) console.log('Error inserting data:', error);
  else console.log('Data inserted:', data);
}

Call insertData() when you need to perform an insertion, such as in an event handler.

 

Step 7: Update Existing Data

 

To update existing records, you can use the update method:


async function updateData() {
  const { data, error } = await supabase
    .from('your_table_name')
    .update({ column_name: 'new_value' })
    .eq('id', 1); // specifying which row to update based on a condition

  if (error) console.log('Error updating data:', error);
  else console.log('Data updated:', data);
}

This code updates the row where id is 1. Replace column_name and new_value with your table's field and new value.

 

Step 8: Delete Data from Supabase

 

To delete records, use the delete method:


async function deleteData() {
  const { data, error } = await supabase
    .from('your_table_name')
    .delete()
    .eq('id', 1); // specifying which row to delete based on a condition

  if (error) console.log('Error deleting data:', error);
  else console.log('Data deleted:', data);
}

This deletes the row where id is 1. Adjust to your needs by changing the condition.

 

Step 9: Enable Realtime Updates (Optional)

 

Supabase supports listening to changes in real-time. Here's an example of how to set this up:


useEffect(() => {
  const subscription = supabase
    .from('your_table_name')
    .on('\*', payload => {
      console.log('Change received!', payload);
      fetchData(); // re-fetch data after any change
    })
    .subscribe();

  return () => {
    supabase.removeSubscription(subscription);
  };
}, []);

Ensure to replace 'your_table_name' appropriately.

 

Conclusion

 

You have set up a React application and integrated it with Supabase for performing CRUD operations. You can expand these examples to suit your needs and build more complex applications by leveraging Supabase's real-time and authentication features.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022