Skip to content

Commit

Permalink
fix: #15 lazy service init
Browse files Browse the repository at this point in the history
  • Loading branch information
supersnager committed Jan 18, 2023
1 parent 343f31a commit 834634e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/provider/ChatProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { TypingUser } from "../TypingUser";
import { useThrottledSendTyping } from "./useThrottledSendTyping";
import { useDebounceTyping } from "./useDebounceTyping";
import type { MessageGroup } from "../MessageGroup";
import { useLazyServiceFactoryRef } from "./useLazyServiceFactoryRef";

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

const serviceRef = useRef(serviceFactory(storage, updateState));
const serviceRef = useLazyServiceFactoryRef(
serviceFactory,
storage,
updateState
);

useStorage(storage, serviceRef.current, setState, {
debounceTyping,
Expand Down
18 changes: 18 additions & 0 deletions src/provider/useLazyServiceFactoryRef.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useRef } from "react";
import type { MutableRefObject } from "react";
import type { ChatServiceFactory, UpdateState } from "../Types";
import type { IChatService, IStorage } from "../interfaces";

export function useLazyServiceFactoryRef<S extends IChatService>(
serviceFactory: ChatServiceFactory<S>,
storage: IStorage,
update: UpdateState
) {
const ref = useRef<S>();

if (typeof ref.current === "undefined") {
ref.current = serviceFactory(storage, update);
}

return ref as MutableRefObject<S>;
}

0 comments on commit 834634e

Please sign in to comment.