From 99a65933fba945cd0af98fa787f12de2a4a65c88 Mon Sep 17 00:00:00 2001 From: Gary Pang Date: Wed, 29 May 2024 00:35:51 -0400 Subject: [PATCH] Refactor onClickSaveButton to improve code legibility Rewrite parts of click handler into helper methods. --- src/components/SinglePropertyDetail.tsx | 65 ++++++++++++++----------- 1 file changed, 36 insertions(+), 29 deletions(-) diff --git a/src/components/SinglePropertyDetail.tsx b/src/components/SinglePropertyDetail.tsx index 515cae7d..1908eed8 100644 --- a/src/components/SinglePropertyDetail.tsx +++ b/src/components/SinglePropertyDetail.tsx @@ -142,38 +142,45 @@ const SinglePropertyDetail = ({ const onClickSaveButton = () => { if (shouldAllowCookies) { - const localStorageData = localStorage.getItem("opa_ids"); - const parsedLocalStorageData = localStorageData - ? JSON.parse(localStorageData) - : {}; + findPropertyIdInLocalStorage(); + } else { + setShouldShowBanner(true); + } + }; - if (parsedLocalStorageData.opa_ids[OPA_ID]) { - removePropertyIdFromLocalStorage(parsedLocalStorageData); - setIsPropertySavedToLocalStorage(false); + const findPropertyIdInLocalStorage = () => { + const localStorageData = localStorage.getItem("opa_ids"); + const parsedLocalStorageData = localStorageData + ? JSON.parse(localStorageData) + : {}; - if (parsedLocalStorageData.count === 0) { - dispatch({ - type: "SET_DIMENSIONS", - property: "OPA_ID", - dimensions: [], - }); - setShouldFilterSavedProperties(false); - } else { - if (shouldFilterSavedProperties) { - let propertyIds = getPropertyIdsFromLocalStorage(); - dispatch({ - type: "SET_DIMENSIONS", - property: "OPA_ID", - dimensions: [...propertyIds], - }); - } - } - } else { - savePropertyIdToLocalStorage(parsedLocalStorageData); - setIsPropertySavedToLocalStorage(true); - } + if (parsedLocalStorageData.opa_ids[OPA_ID]) { + removePropertyIdFromLocalStorage(parsedLocalStorageData); + setIsPropertySavedToLocalStorage(false); + dispatchFilterAction(parsedLocalStorageData); } else { - setShouldShowBanner(true); + savePropertyIdToLocalStorage(parsedLocalStorageData); + setIsPropertySavedToLocalStorage(true); + } + }; + + const dispatchFilterAction = (data: any) => { + if (data.count === 0) { + dispatch({ + type: "SET_DIMENSIONS", + property: "OPA_ID", + dimensions: [], + }); + setShouldFilterSavedProperties(false); + } else { + if (shouldFilterSavedProperties) { + let propertyIds = getPropertyIdsFromLocalStorage(); + dispatch({ + type: "SET_DIMENSIONS", + property: "OPA_ID", + dimensions: [...propertyIds], + }); + } } };