From ca36fe21c0c78c33ab059290337a03daa9b5f7fb Mon Sep 17 00:00:00 2001 From: Tsu-ba-me Date: Fri, 12 Aug 2022 14:51:26 -0400 Subject: [PATCH] fix(striker-ui): generate message keys only when necessary in MessageGroup --- striker-ui/components/MessageGroup.tsx | 32 ++++++++++++-------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/striker-ui/components/MessageGroup.tsx b/striker-ui/components/MessageGroup.tsx index 331a32e5..f614d876 100644 --- a/striker-ui/components/MessageGroup.tsx +++ b/striker-ui/components/MessageGroup.tsx @@ -1,6 +1,7 @@ import { forwardRef, useCallback, + useEffect, useImperativeHandle, useMemo, useState, @@ -36,23 +37,7 @@ const MessageGroup = forwardRef< }, ref, ) => { - const { keys: messageKeys } = useMemo( - () => - Array.from({ length: count }).reduce<{ - keys: string[]; - }>( - (previous) => { - const { keys } = previous; - - keys.push(uuidv4()); - - return previous; - }, - { keys: [] }, - ), - [count], - ); - + const [messageKeys, setMessageKeys] = useState([]); const [messages, setMessages] = useState>([]); const setMessage = useCallback((index: number, message?: Message) => { @@ -94,6 +79,19 @@ const MessageGroup = forwardRef< [defaultMessageType, messages, messageKeys], ); + useEffect(() => { + setMessageKeys((previous) => { + const result = [...previous]; + const diff = count - result.length; + + if (diff > 0) { + result.push(...Array.from({ length: diff }, () => uuidv4())); + } + + return result; + }); + }, [count]); + useImperativeHandle(ref, () => ({ setMessage }), [setMessage]); return <>{messageElements};