Supabase realtime Collaboration

Add real-time collaboration to Spreadsheet 2 using Supabase

You can install Supabase hook as a separate module

yarn add "@rowsncolumns/supabase-spreadsheet"

Initializing Supabase

Create a supabase client and pass it to useSupabaseSpreadsheet hook

const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_KEY,
  {
    realtime: {
      params: {
        eventsPerSecond: 20,
      },
    },
  }
);

This hook does not save state in the server side, but rather synchronizes ephemeral state updates between connected clients.

import {
  SheetData,
  useSpreadsheetState,
} from "@rowsncolumns/spreadsheet-state";
import { useSupabaseSpreadsheet } from "@rowsncolumns/supabase-spreadsheet"
import { SpreadsheetProvider, CanvasGrid } from '@rowsncolumns/spreadsheet'

const MySpreadsheet = () => {
  const userId = 'foobar'
  const name = 'foobar'
  const [sheets, onChangeSheets] = useState<Sheet[]>([]);
  const [sheetData, onChangeSheetData] = useState<SheetData<CellData>>({});
  const [tables, onChangeTables] = useState<TableView[]>([]);
  
  const { activeCell, activeSheetId, enqueueCalculation, ... } = useSpreadsheetState({
    ....,
    onChangeHistory(patches) {
      // Send to all clients
      onBroadcastPatch(patches);
      
      // TODO
      // Persist state to the server side
    },
  })
  
  // Add Supabase hook
  const { users, onBroadcastPatch } = useSupabaseSpreadsheet({
    supabase,
    userId,
    userName: `Username - ${userId}`,
    activeCell,
    sheetId: activeSheetId,
    onChangeSheetData,
    enqueueCalculation,
    onChangeSheets,
    onChangeTables,
  });


  return (
    <CanvasGrid
      {...}
      users={users}
      userId={userId}
    >
  )

}

const App = () => (
  <SpreadsheetProvider>
    <MySpreadsheet />
  </SpreadsheetProvider>
)

Last updated