Skip to content

Selfdb-io/selfdb-react-vite

Repository files navigation

Open Discussion Board - SelfDB JS SDK Demo

A React-based discussion board application built with the SelfDB JavaScript SDK. This app demonstrates how to build a full-featured application using SelfDB for backend services.

Features

  • πŸ“ Topic Creation: Create discussion topics with rich text and file attachments
  • πŸ’¬ Comments: Reply to topics with threaded comments
  • πŸ“Ž File Attachments: Upload and share images, videos, audio, and documents
  • πŸ‘€ User Authentication: Login/register or post anonymously
  • ⚑ Real-time Updates: Live updates when new topics and comments are added
  • πŸ“± Responsive Design: Works on desktop and mobile devices
  • 🎨 Modern UI: Built with Tailwind CSS and shadcn/ui components

Built With

  • Frontend: React 18, TypeScript, Vite
  • Styling: Tailwind CSS, shadcn/ui components
  • Backend: SelfDB with JavaScript SDK
  • Database: PostgreSQL (via SelfDB)
  • Storage: SelfDB Storage Service
  • Real-time: WebSocket connections (via SelfDB)

Prerequisites

  1. Running SelfDB Instance: Make sure SelfDB is running on http://localhost:8000
  2. Node.js: Version 16 or higher
  3. SelfDB Anonymous Key: Available in your SelfDB .env file

Quick Setup

  1. Run the setup script:

    ./setup.sh

    This will:

    • Copy the anonymous key from your SelfDB instance
    • Install the SelfDB JS SDK from the local build
    • Install all other dependencies
    • Create the necessary environment configuration
  2. Start the development server:

    npm run dev
  3. Open the app: Navigate to http://localhost:5173

Manual Setup

If you prefer to set up manually:

  1. Install dependencies:

    npm install
    npm install ../../js-sdk  # Install local SelfDB JS SDK
  2. Create .env file:

    VITE_SELFDB_URL=http://localhost:8000
    VITE_SELFDB_STORAGE_URL=http://localhost:8001
    VITE_SELFDB_ANON_KEY=your_anon_key_here
  3. Start development server:

    npm run dev

Database Schema

The app expects these tables in your SelfDB instance:

Topics Table

CREATE TABLE topics (
  id SERIAL PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  content TEXT NOT NULL,
  author_name VARCHAR(255) NOT NULL,
  user_id INTEGER REFERENCES users(id),
  file_id INTEGER,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

Comments Table

CREATE TABLE comments (
  id SERIAL PRIMARY KEY,
  topic_id INTEGER REFERENCES topics(id) ON DELETE CASCADE,
  content TEXT NOT NULL,
  author_name VARCHAR(255) NOT NULL,
  user_id INTEGER REFERENCES users(id),
  file_id INTEGER,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

Note: The tables will be created automatically when you create your first topic or comment.

Key Features Demonstrated

SelfDB SDK Usage

  1. Authentication:

    // Login
    await selfdb.auth.login({ email, password })
    
    // Register
    await selfdb.auth.register({ email, password })
    
    // Anonymous access (automatic fallback)
  2. Database Operations:

    // Create records
    const topic = await selfdb.db.create('topics', topicData)
    
    // Read with filters and sorting
    const topics = await selfdb.db.read('topics', {
      orderBy: [{ column: 'created_at', direction: 'desc' }],
      limit: 50
    })
    
    // Find by ID
    const topic = await selfdb.db.findById('topics', id)
  3. File Storage:

    // Create bucket
    const bucket = await selfdb.storage.buckets.createBucket({
      name: 'discussion-files',
      is_public: true
    })
    
    // Upload file
    const result = await selfdb.storage.files.uploadFile(bucketId, file)
    
    // Download file
    const blob = await selfdb.storage.files.downloadFile(bucketId, fileId)
  4. Real-time Updates:

    // Connect to real-time
    await selfdb.realtime.connect()
    
    // Subscribe to table changes
    selfdb.realtime.subscribe('topics', (payload) => {
      console.log('Topics updated:', payload)
    })

Anonymous vs Authenticated Users

  • Anonymous users can create topics and comments without registration
  • Authenticated users get their email associated with posts
  • Both can upload files and receive real-time updates
  • Anonymous access uses the anonKey automatically

File Upload Support

  • Supported formats: Images, videos, audio, PDFs
  • File size limit: 10MB per file
  • Preview support: Images and videos show inline previews
  • Download capability: All files can be downloaded
  • Public storage: Files are stored in public buckets for easy access

Project Structure

src/
β”œβ”€β”€ components/          # React components
β”‚   β”œβ”€β”€ ui/             # Reusable UI components
β”‚   β”œβ”€β”€ Header.tsx      # Navigation header
β”‚   β”œβ”€β”€ Login.tsx       # Login modal
β”‚   β”œβ”€β”€ Register.tsx    # Registration modal
β”‚   β”œβ”€β”€ CreateTopic.tsx # Topic creation form
β”‚   β”œβ”€β”€ TopicCard.tsx   # Topic list item
β”‚   β”œβ”€β”€ TopicList.tsx   # Main topics page
β”‚   β”œβ”€β”€ TopicDetail.tsx # Individual topic view
β”‚   └── FilePreview.tsx # File attachment preview
β”œβ”€β”€ contexts/           # React contexts
β”‚   └── AuthContext.tsx # Authentication state
β”œβ”€β”€ services/          # API services
β”‚   └── selfdb.ts      # SelfDB client configuration
β”œβ”€β”€ types/             # TypeScript type definitions
β”œβ”€β”€ lib/               # Utility functions
└── App.tsx            # Main application component

Available Scripts

  • npm run dev - Start development server
  • npm run build - Build for production
  • npm run preview - Preview production build
  • npm run lint - Run ESLint

Environment Variables

Variable Description Default
VITE_SELFDB_URL SelfDB API URL http://localhost:8000
VITE_SELFDB_STORAGE_URL SelfDB Storage URL http://localhost:8001
VITE_SELFDB_ANON_KEY Anonymous API key (required)

Troubleshooting

Common Issues

  1. "VITE_SELFDB_ANON_KEY is required"

    • Make sure you've run ./setup.sh or manually set the environment variable
    • Check that your main SelfDB .env file has an ANON_KEY
  2. Connection errors

    • Ensure SelfDB is running on http://localhost:8000
    • Check that all services are healthy in your SelfDB instance
  3. File upload failures

    • Check file size (must be < 10MB)
    • Ensure storage service is running on http://localhost:8001
    • Verify the bucket has proper permissions
  4. Real-time not working

    • Check browser console for WebSocket connection errors
    • Ensure SelfDB realtime service is enabled

Development Tips

  • Use browser dev tools to monitor network requests
  • Check the SelfDB admin panel for database records
  • Monitor the console for real-time events
  • Test with both authenticated and anonymous users

Contributing

This is a demo application showcasing SelfDB capabilities. Feel free to:

  • Add new features to demonstrate additional SDK capabilities
  • Improve the UI/UX
  • Add tests
  • Optimize performance

License

This sample application is provided as-is for demonstration purposes.

About

Selfdb React Vite App

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published