Chatroom

Frontend

Syncing Data

  • To update chat history on local DB on background

useSyncMessages.ts
import { useEffect, useRef } from "react";

import { AppState } from "react-native";

import { syncMessages } from "@/lib/features/chat/conversation-init";
import { useAuth } from "@/lib/store/authStore";
import { logger } from "@/lib/utils/logger";

import type { AppStateStatus } from "react-native";

const SYNC_INTERVAL_MS = 60_000; // 1 minute

export const useSyncMessages = () => {
  const { user } = useAuth();
  const appStateRef = useRef<AppStateStatus>(AppState.currentState);

  useEffect(() => {
    if (!user?.id) return;

    logger.debug("syncMessages");
    // 1. Sync on initial load
    syncMessages();

    // 2. Sync on app foreground
    const subscription = AppState.addEventListener("change", (nextAppState) => {
      if (
        appStateRef.current.match(/inactive|background/) &&
        nextAppState === "active"
      ) {
        syncMessages();
      }
      appStateRef.current = nextAppState;
    });

    // 3. Periodic sync every 1 minute
    const intervalId = setInterval(syncMessages, SYNC_INTERVAL_MS);

    return () => {
      subscription.remove();
      clearInterval(intervalId);
    };
  }, [user?.id]);
};

Fetching Chat History

  • Keep fetching chat history from local DB / remote database

  • Display the chat history on UI

Web socket

  • To listen to the message event for frontend handling

Send Message

  • To send the message through backend

  • Handle different type of message, e.g: image, video, text

  • Store the sent message to local db

Backend

Send Message

  • Store the message to database

  • Emit the message for web socket

  • Handle join room/conversation by listening event

Last updated