realtime-chat-supabase-react

repository·master·Indexed 21 days ago

https://github.com/shwosner/realtime-chat-supabase-react

A full-stack real-time chat application built with React, Vite, and Chakra UI, utilizing Supabase for PostgreSQL database management and real-time capabilities. Version 0.3.0.

Tokens
3.3K
Snippets
18
Records
18
Agent score
74%

What's inside realtime-chat-supabase-react

  1. Setup the Supabase `messages` table

    master

    The application relies on a messages table in your Supabase PostgreSQL database. You can create this table using the Supabase dashboard interface or by executing the following SQL query in the Supabase SQL Editor:

    Important: If you create the table via the Supabase UI, you must manually enable the Enable Realtime setting for the messages table to allow real-time chat functionality.

    CREATE TABLE messages (
      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
    );
  2. Configure Supabase environment variables

    master

    The application requires connection details for your Supabase instance. Create a .env file in the root directory and populate it with the following variables (you can refer to env.example for the template):

    VITE_SUPABASE_URL=your_supabase_url
    VITE_SUPABASE_KEY=your_supabase_anon_key
  3. Register a service worker for PWA capabilities

    master

    To enable offline capabilities and faster subsequent loads via a Progressive Web App (PWA) model, use the register function. Note that service workers are only registered when process.env.NODE_ENV is set to 'production' and the browser supports serviceWorker in navigator.

    Registration is not enabled by default and must be explicitly called in your application entry point. You can provide a config object to handle lifecycle events like successful installation or content updates.

    import { register } from './serviceWorker';
    
    register({
      onSuccess: (registration) => {
        console.log('Content is cached for offline use.');
      },
      onUpdate: (registration) => {
        console.log('New content is available and will be used when all tabs for this page are closed.');
      }
    });
  4. Configure service worker lifecycle callbacks

    master

    When calling register(config), you can pass a config object to intercept specific service worker lifecycle events:

    • onSuccess: Triggered when the service worker has finished precaching everything. This is the ideal time to notify the user that the app is ready for offline use.
    • onUpdate: Triggered when a new service worker has been installed but is waiting to activate. This happens when updated content is available but the current version is still being served by existing open tabs.
    register({
      onSuccess: (registration) => {
        // Handle successful precaching
      },
      onUpdate: (registration) => {
        // Handle discovery of new content
      }
    });
  5. Truncate text with truncateText

    master

    The truncateText utility function shortens a string to a specified maximum length and appends an ellipsis (...) if the string exceeds that length. If the text is shorter than or equal to the maxLength, the original text is returned unchanged.

    import { truncateText } from './utils/index.js';
    
    const longText = "This is a very long string that needs to be shortened.";
    const shortText = truncateText(longText, 10);
    // Returns: "This is a ve..."
    
    const normalText = truncateText("Hello", 10);
    // Returns: "Hello"
  6. Use the toaster instance to trigger notifications

    master

    The project exports a pre-configured toaster instance created via Chakra UI's createToaster. You can import this instance into any client component to trigger toast notifications (e.g., success, error, or loading states) throughout the application. The default configuration places notifications at the bottom-end of the viewport and pauses them when the page is idle.

    import { toaster } from "@/components/ui/toaster";
    
    // Example usage:
    // toaster.create({
    //   title: "Success",
    //   description: "Message sent!",
    //   color: "green.solid",
    // });
  7. Setup the ColorModeProvider

    master

    Wrap your application with ColorModeProvider to enable theme management. It uses next-themes under the hood with the class attribute, meaning theme changes will apply a .light or .dark class to the HTML element. By default, it is set to light mode and does not follow system preferences (enableSystem={false}).

    import { ColorModeProvider } from './components/ui/color-mode'
    
    function App({ children }) {
      return (
        <ColorModeProvider>
          {children}
        </ColorModeProvider>
      )
    }
  8. Use the useColorMode hook

    master

    The useColorMode hook provides access to the current theme state and methods to manipulate it.

    Returns:

    • colorMode: The current active theme ('light' or 'dark').
    • setColorMode: A function to explicitly set the theme (e.g., setColorMode('dark')).
    • toggleColorMode: A function that switches between 'light' and 'dark' modes.
    import { useColorMode } from './components/ui/color-mode'
    
    function MyComponent() {
      const { colorMode, setColorMode, toggleColorMode } = useColorMode()
    
      return (
        <div>
          <p>Current mode: {colorMode}</p>
          <button onClick={toggleColorMode}>Toggle</button>
          <button onClick={() => setColorMode('light')}>Force Light</button>
        </div>
      )
    }