From b00afbe7cfae3938bc77c30390c4b40f5c2ebbd1 Mon Sep 17 00:00:00 2001 From: Tsu-ba-me Date: Sat, 1 Apr 2023 02:03:35 -0400 Subject: [PATCH] fix(striker-ui): avoid depend on outdated message list in MessageGroup setters --- striker-ui/components/MessageGroup.tsx | 47 ++++++++++++++------------ 1 file changed, 26 insertions(+), 21 deletions(-) diff --git a/striker-ui/components/MessageGroup.tsx b/striker-ui/components/MessageGroup.tsx index 1ada5852..1bfda7ad 100644 --- a/striker-ui/components/MessageGroup.tsx +++ b/striker-ui/components/MessageGroup.tsx @@ -62,20 +62,22 @@ const MessageGroup = forwardRef< (key: string, message?: Message) => { let length = 0; - const { [key]: unused, ...rest } = messages; - const result: Messages = rest; + setMessages((previous) => { + const { [key]: unused, ...rest } = previous; + const result: Messages = rest; - if (message) { - result[key] = message; - } + if (message) { + result[key] = message; + } - length = Object.keys(result).length; + length = Object.keys(result).length; - onSet?.call(null, length); + return result; + }); - setMessages(result); + onSet?.call(null, length); }, - [messages, onSet], + [onSet], ); const setMessageRe = useCallback( (re: RegExp, message?: Message) => { @@ -87,22 +89,25 @@ const MessageGroup = forwardRef< length += 1; } : undefined; - const result: Messages = {}; - - Object.keys(messages).forEach((key: string) => { - if (re.test(key)) { - assignMessage?.call(null, result, key); - } else { - result[key] = messages[key]; - length += 1; - } + + setMessages((previous) => { + const result: Messages = {}; + + Object.keys(previous).forEach((key: string) => { + if (re.test(key)) { + assignMessage?.call(null, result, key); + } else { + result[key] = previous[key]; + length += 1; + } + }); + + return result; }); onSet?.call(null, length); - - setMessages(result); }, - [messages, onSet], + [onSet], ); const messageElements = useMemo(() => {