Integrating Supabase with React: Fetching Data......

Integrating Supabase with React: Fetching Data and Submitting Form Details

Integrating Supabase with React: Fetching Data and Submitting Form Details

Supabase is an open-source Firebase alternative that provides a powerful backend with an easy-to-use API. In this blog post, we'll explore how to integrate Supabase with a React project to fetch data from a database and add form details.

Getting Started with Supabase and React

Before diving in, ensure you have the following:

  • A React project set up.
  • A Supabase account. If you don't have one, sign up at supabase.com.
  • A Supabase project created with a table to store your form details.

Step 1: Setting Up Supabase in Your React Project

First, you need to install the Supabase client in your React project. Run the following command:


npm install @supabase/supabase-js

Next, create a file named supabaseClient.js in your project to initialize the Supabase client:

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

const supabaseUrl = 'https://your-project-url.supabase.co';
const supabaseKey = 'your-anon-key';

export const supabase = createClient(supabaseUrl, supabaseKey);

Replace your-project-url and your-anon-key with your actual Supabase project URL and API key from the Supabase dashboard.

Step 2: Fetching Data from Supabase

To fetch data from Supabase, you can use the following code snippet in a React component:

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

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

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

  const fetchData = async () => {
    const { data, error } = await supabase
      .from('your_table_name')
      .select('*');

    if (error) {
      console.error('Error fetching data:', error);
    } else {
      setData(data);
    }
  };

  return (
    <div>
      <h2>Fetched Data</h2>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default DataList;

Explanation

  • Fetching Data: The fetchData function uses Supabase's select method to fetch all rows from the specified table.
  • Displaying Data: The fetched data is stored in the data state and displayed in a list.

Step 3: Adding Form Details to Supabase

Next, let's integrate a form that submits data to Supabase. Here's a basic form setup:

import React, { useState } from 'react';
import { supabase } from './supabaseClient';
import TextField from '@mui/material/TextField';

function ContactForm() {
  const [formValues, setFormValues] = useState({
    name: '',
    email: '',
    phone: '',
    about: '',
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormValues({ ...formValues, [name]: value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const { data, error } = await supabase
      .from('your_table_name')
      .insert([
        { name: formValues.name, email: formValues.email, phone: formValues.phone, about: formValues.about },
      ]);

    if (error) {
      console.error('Error inserting data:', error);
    } else {
      console.log('Data inserted successfully:', data);
      // Clear the form
      setFormValues({
        name: '',
        email: '',
        phone: '',
        about: '',
      });
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <TextField
        name="name"
        label="Name"
        value={formValues.name}
        onChange={handleChange}
        required
      />
      <TextField
        name="email"
        label="Email"
        value={formValues.email}
        onChange={handleChange}
        required
      />
      <TextField
        name="phone"
        label="Phone"
        value={formValues.phone}
        onChange={handleChange}
        required
      />
      <TextField
        name="about"
        label="About"
        value={formValues.about}
        onChange={handleChange}
        multiline
        rows={4}
        required
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default ContactForm;

Explanation

  • Form Handling: The handleChange function updates the form values as the user types in the input fields.
  • Form Submission: The handleSubmit function inserts the form details into the specified Supabase table.

Step 4: Integrating the Components

Finally, you can integrate the DataList and ContactForm components in your main app component:

import React from 'react';
import DataList from './DataList';
import ContactForm from './ContactForm';

function App() {
  return (
    <div>
      <h1>Supabase React Integration</h1>
      <ContactForm />
      <DataList />
    </div>
  );
}

export default App;

Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts