Skip to content

Commit 834634e

Browse files
committed
fix: #15 lazy service init
1 parent 343f31a commit 834634e

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

src/provider/ChatProvider.tsx

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import { TypingUser } from "../TypingUser";
2929
import { useThrottledSendTyping } from "./useThrottledSendTyping";
3030
import { useDebounceTyping } from "./useDebounceTyping";
3131
import type { MessageGroup } from "../MessageGroup";
32+
import { useLazyServiceFactoryRef } from "./useLazyServiceFactoryRef";
3233

3334
export interface SendMessageParams {
3435
message: ChatMessage<MessageContentType>;
@@ -306,7 +307,11 @@ export const ChatProvider = <S extends IChatService>({
306307
setState(newState);
307308
}, [setState, storage]);
308309

309-
const serviceRef = useRef(serviceFactory(storage, updateState));
310+
const serviceRef = useLazyServiceFactoryRef(
311+
serviceFactory,
312+
storage,
313+
updateState
314+
);
310315

311316
useStorage(storage, serviceRef.current, setState, {
312317
debounceTyping,
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { useRef } from "react";
2+
import type { MutableRefObject } from "react";
3+
import type { ChatServiceFactory, UpdateState } from "../Types";
4+
import type { IChatService, IStorage } from "../interfaces";
5+
6+
export function useLazyServiceFactoryRef<S extends IChatService>(
7+
serviceFactory: ChatServiceFactory<S>,
8+
storage: IStorage,
9+
update: UpdateState
10+
) {
11+
const ref = useRef<S>();
12+
13+
if (typeof ref.current === "undefined") {
14+
ref.current = serviceFactory(storage, update);
15+
}
16+
17+
return ref as MutableRefObject<S>;
18+
}

0 commit comments

Comments
 (0)