diff --git a/react-chat/src/App.tsx b/react-chat/src/App.tsx index c153168..876d597 100644 --- a/react-chat/src/App.tsx +++ b/react-chat/src/App.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react' +import {useEffect, useMemo, useState} from 'react' import { AnyDocumentId, DocHandle, Repo } from '@automerge/automerge-repo'; import { BrowserWebSocketClientAdapter } from '@automerge/automerge-repo-network-websocket'; import { IndexedDBStorageAdapter } from '@automerge/automerge-repo-storage-indexeddb'; @@ -8,6 +8,7 @@ import { Chat } from './components/Chat' import { UserSettings } from './components/UserSettings' import { LoginRequiredError, createClient, createVerifier } from '@featherscloud/auth' import { ChatDocument, CloudAuthUser, Message, User, sha256 } from './utils'; +import {ChatContext, ChatContextValue} from "./components/ChatContext.tsx"; // Initialize Feathers Cloud Auth const appId = import.meta.env.VITE_CLOUD_APP_ID as string; @@ -48,20 +49,6 @@ function App() { } } - // Create a new Message - const createMessage = (text: string) => { - if (handle && user) { - handle.change(doc => { - doc.messages.push({ - id: crypto.randomUUID(), - text: text, - createdAt: Date.now(), - userId: user.id - }) - }) - } - } - // Initialize the application const init = async () => { try { @@ -91,6 +78,8 @@ function App() { } } + const contextValue = useMemo(()=>({user, handle}), [user, handle]); + useEffect(() => { init() }, []) @@ -98,7 +87,7 @@ function App() { if (handle?.isReady()) { return user === null ? - : + : } } diff --git a/react-chat/src/components/Chat.tsx b/react-chat/src/components/Chat.tsx index 09a7d76..7216a49 100644 --- a/react-chat/src/components/Chat.tsx +++ b/react-chat/src/components/Chat.tsx @@ -1,15 +1,31 @@ import { Message, User } from "../utils"; import { CreateMessage } from "./CreateMessage" import { MessageList } from "./MessageList" +import {useChat} from "./ChatContext.tsx"; +import {useCallback} from "react"; export type ChatOptions = { - user: User; users: User[]; messages: Message[]; - createMessage: (text: string) => void; }; -export const Chat = ({ messages, user, users, createMessage }: ChatOptions) => { +export const Chat = ({ messages, users }: ChatOptions) => { + const {user, handle} = useChat(); + + // Create a new Message + const createMessage = useCallback((text: string) => { + if (handle && user) { + handle.change(doc => { + doc.messages.push({ + id: crypto.randomUUID(), + text: text, + createdAt: Date.now(), + userId: user.id + }) + }) + } + }, [user, handle]) + return
@@ -34,7 +50,7 @@ export const Chat = ({ messages, user, users, createMessage }: ChatOptions) => {