Skip to main content

Create an Application from Scratch

The example Real Time Chat Application gives you a good idea of the features of Supabase. But let us create a new react application from scratch. This will allow you to see the Supabase parts and ignore the react specifics.

Setup React​

  1. Create a new react application

    npx create-react-app supabase-demo
  2. Change directory into the new application

    cd supabase-demo
  3. Install Supabase

    npm install @supabase/supabase-js
  4. In src/App.js replace the code with following

    import './App.css';

    export default function App() {
    // state management

    // subscribe to message

    // handle message sent

    return (
    <div className="App">
    </div>
    );
    }
  5. Run the application

    npm start

    You will see nothing. Because there is nothing in our src/App.js file.

  6. At the root of the repository, create a .env file and populate with the following

    REACT_APP_ANON_KEY="<SUPABASE_ANON_KEY>"
    REACT_APP_API_URL="<SUPABASE_API_URL>"

Setup Supabase​

  1. In Supabase studio, create a new project if you dont have already. You can also reuse an existing project. In the project go to SQL Editor and create a new Table.
    CREATE TABLE texts (
    id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    username VARCHAR NOT NULL,
    text TEXT NOT NULL,
    country VARCHAR,
    is_authenticated BOOLEAN DEFAULT FALSE,
    timestamp timestamp default now() NOT NULL
    );
    This is an identical table schema as you had in the previous section. Just the name of the table is different.

Creating the Supabase Client​

  1. In src/App.js import supabase
    import { createClient } from '@supabase/supabase-js';
  2. Inside App() function initialize the client
    const supabaseUrl = process.env.REACT_APP_API_URL;
    const supabaseKey = process.env.REACT_APP_ANON_KEY;
    const supabase = createClient(supabaseUrl, supabaseKey);

Subscribe to messages​

  1. Supabase is a BaaS (Backend as a Service). It creates all the CRUD operations for you.

    const getInitialMessages = async () => {
    if (!messages.length) {
    const { data, error } = await supabase
    .from('texts')
    .select()
    .range(0, 50)
    .order('id', { ascending: false });
    if (error) {
    setError(error);
    supabase.removeSubscription(subscription);
    subscription = null;
    return;
    }
    setMessages((prevMessages) => [...prevMessages, ...data]);
    }
    };
  2. It also provides a way to subscribe to changes in the database.

    const handleNewMessage = (payload) => {
    setMessages((messages) => [payload.new, ...messages]);
    };

    const getMessagesAndSubscribe = async () => {
    setError('');
    if (!subscription) {
    getInitialMessages();
    subscription = supabase
    .from('texts')
    .on('*', (payload) => {
    handleNewMessage(payload);
    })
    .subscribe();
    }
    };

Handle message send​

  1. You can also use the Supabase client to insert data into the database

    const sendMessage= async (e) => {
    e.preventDefault();
    if (!text) {
    return;
    }
    try {
    const { error } = await supabase.from("texts").insert([
    {
    text: text,
    username: username,
    },
    ]);

    if (error) {
    console.error(error.message);
    return;
    }
    console.log("Sucsessfully sent!");
    } catch (error) {
    console.log("error sending message:", error);
    }
    setText('');
    }

Putting it all together​

  1. The final src/App.js looks like this
note

You can get access to the codebase at https://github.com/moficodes/supabase-demo

Running the application​

  1. You can run the application with npm start
  2. You can access the application at port 3000
  3. The application is not yet realtime. Follow the steps from previous section