From 4137b1fbd0bc6997065e3cd4c59bcf55940cd083 Mon Sep 17 00:00:00 2001 From: mannipje <135017126+mannipje@users.noreply.github.com> Date: Mon, 2 Dec 2024 12:34:50 +0000 Subject: [PATCH] fix(contentful-apps): Fix chart component manual data key value on page load (#17086) Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> --- .../chart-component-source-data-key-field.tsx | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/apps/contentful-apps/pages/fields/chart-component-source-data-key-field.tsx b/apps/contentful-apps/pages/fields/chart-component-source-data-key-field.tsx index 16b4614e49b5..bc1f49a695ee 100644 --- a/apps/contentful-apps/pages/fields/chart-component-source-data-key-field.tsx +++ b/apps/contentful-apps/pages/fields/chart-component-source-data-key-field.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import NumberFormat from 'react-number-format' import { useDebounce } from 'react-use' import { FieldExtensionSDK } from '@contentful/app-sdk' @@ -84,6 +84,9 @@ const ChartComponentSourceDataKeyField = () => { }, ) const typeOfSource = manualData ? manualData['typeOfSource'] : null + const typeOfManualDataKey = manualData + ? manualData['typeOfManualDataKey'] + : null const typeIsPieChart = sdk.entry.fields.type.getValue() === 'pie-cell' const externalSourceDataKey = manualData @@ -96,7 +99,7 @@ const ChartComponentSourceDataKeyField = () => { const [textInput, setTextInput] = useState(externalSourceDataKey) const [manualDataKeyValue, setManualDataKeyValue] = useState( - typeIsPieChart ? ManualDataKeyValues.Category : ManualDataKeyValues.Date, + typeOfManualDataKey ?? ManualDataKeyValues.Date, ) const componentKeyValue = sdk.ids.entry @@ -105,15 +108,27 @@ const ChartComponentSourceDataKeyField = () => { sdk.window.startAutoResizer() }, [sdk.window]) + const isInitialLoad = useRef(true) useEffect(() => { - sdk.entry.fields.type.onValueChanged((type) => { + const unsubscribe = sdk.entry.fields.type.onValueChanged((type) => { + if (isInitialLoad.current) { + // Skip the first trigger on page load + isInitialLoad.current = false + return + } + if (type === 'pie-cell') { setManualDataKeyValue(ManualDataKeyValues.Category) } else { setManualDataKeyValue(ManualDataKeyValues.Date) } }) - }, [sdk.entry.fields.type]) + + // Cleanup listener on unmount + return () => { + unsubscribe() + } + }, [sdk.entry.fields.type, setManualDataKeyValue]) useDebounce( () => {