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β
Create a new react application
npx create-react-app supabase-demoChange directory into the new application
cd supabase-demoInstall Supabase
npm install @supabase/supabase-jsIn
src/App.jsreplace the code with followingimport './App.css';
export default function App() {
// state management
// subscribe to message
// handle message sent
return (
<div className="App">
</div>
);
}Run the application
npm startYou will see nothing. Because there is nothing in our
src/App.jsfile.At the root of the repository, create a
.envfile and populate with the followingREACT_APP_ANON_KEY="<SUPABASE_ANON_KEY>"
REACT_APP_API_URL="<SUPABASE_API_URL>"
Setup Supabaseβ
- 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 Editorand create a new Table.This is an identical table schema as you had in the previous section. Just the name of the table is different.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
);
Creating the Supabase Clientβ
- In
src/App.jsimportsupabaseimport { createClient } from '@supabase/supabase-js'; - Inside
App()function initialize the clientconst supabaseUrl = process.env.REACT_APP_API_URL;
const supabaseKey = process.env.REACT_APP_ANON_KEY;
const supabase = createClient(supabaseUrl, supabaseKey);
Subscribe to messagesβ
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]);
}
};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β
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β
- The final
src/App.jslooks like this
note
You can get access to the codebase at https://github.com/moficodes/supabase-demo
Running the applicationβ
- You can run the application with
npm start - You can access the application at port
3000 - The application is not yet realtime. Follow the steps from previous section