From 6b2569aed022a0081652130815f5587de53e6d84 Mon Sep 17 00:00:00 2001 From: evlist Date: Thu, 2 Mar 2023 11:33:38 +0100 Subject: [PATCH] Logic for subscriptions add/remove --- src/components/user/User.tsx | 50 +++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/src/components/user/User.tsx b/src/components/user/User.tsx index a5ffe10..68fc63a 100644 --- a/src/components/user/User.tsx +++ b/src/components/user/User.tsx @@ -49,9 +49,45 @@ const User: Component = (props) => { }; await put(couchUserId, userDoc, isNew(), '_users'); - if (isNew()) { - navigate(`/user/${id}`); + const subscriptions = !!props?.values + ? props.values().subscriptions ?? [] + : []; + const updatedSubscriptions = values.subscriptions ?? []; + + const isIn = (username: string, subs: any[]) => { + for (let i = 0; i < subs.length; i++) { + let sub = subs[i]; + if (username === sub.username) { + return true; + } + } + return false; + }; + + for (let i = 0; i < updatedSubscriptions.length; i++) { + let subscription = updatedSubscriptions[i]; + if (!isIn(subscription.username, subscriptions)) { + console.log({ + caller: 'User / submitHandler / new subscription', + username: subscription.username, + }); + } } + + for (let i = 0; i < subscriptions.length; i++) { + let subscription = subscriptions[i]; + if (!isIn(subscription.username, updatedSubscriptions)) { + console.log({ + caller: 'User / submitHandler / deleted subscription', + username: subscription.username, + }); + } + } + + setInitialValues(values); + setIsDirty(false); + + navigate(`/user/${id}`); }; const cancelHandler = () => { @@ -116,6 +152,7 @@ const User: Component = (props) => { form, data, setData, + setIsDirty, setInitialValues, reset, addField, @@ -141,12 +178,17 @@ const User: Component = (props) => { const subscriptions = () => data('subscriptions'); function removeSubscription(index: number) { - return () => unsetField(`subscriptions.${index}`); + return () => { + unsetField(`subscriptions.${index}`); + setIsDirty(true); + }; } function addSubscription(index?: number) { - return () => + return () => { addField(`subscriptions`, { username: '', direction: '' }, index); + setIsDirty(true); + }; } console.log({