diff --git a/modules/dxp/apps/commerce/commerce-dashboard-web/src/main/resources/META-INF/resources/js/ForecastChart.js b/modules/dxp/apps/commerce/commerce-dashboard-web/src/main/resources/META-INF/resources/js/ForecastChart.js index adcd0d31eb439a..fa454798184a6c 100644 --- a/modules/dxp/apps/commerce/commerce-dashboard-web/src/main/resources/META-INF/resources/js/ForecastChart.js +++ b/modules/dxp/apps/commerce/commerce-dashboard-web/src/main/resources/META-INF/resources/js/ForecastChart.js @@ -3,40 +3,61 @@ * SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06 */ -import React, {useEffect, useState} from 'react'; +import React, {useCallback, useEffect, useState} from 'react'; import ChartWrapper from './ChartWrapper'; import {loadData} from './utils/index.es'; export default function ForecastChart({ APIBaseUrl, - accountIds: initialAccountsIds = [], - categoryIds = [], + accountIds: rawAccountIds = '[]', + categoryIds: rawCategoryIds = '[]', }) { + let accountsIds; + let categoryIds; + + try { + accountsIds = JSON.parse(rawAccountIds); + categoryIds = JSON.parse(rawCategoryIds); + } + catch (error) { + console.error(`Parse error:`, error); + } + const [loading, setLoading] = useState(true); const [chartData, setChartData] = useState({}); - const [accountsId, setAccountId] = useState(initialAccountsIds); - Liferay.on('accountSelected', ({accountId}) => setAccountId([accountId])); - function updateData() { + const [accountsId, setAccountId] = useState(accountsIds); + + const updateData = useCallback(() => { const formattedAccountIds = accountsId .map((id) => `accountIds=${id}`) .join('&'); const formattedCategoryIds = categoryIds.length ? '&' + categoryIds.map((id) => `categoryIds=${id}`).join('&') : ''; + const APIUrl = `${APIBaseUrl}?${formattedAccountIds}${formattedCategoryIds}&pageSize=200`; - startLoading(); - loadData(APIUrl).then(setChartData); - } - function stopLoading() { - setLoading(!chartData.data); - } - function startLoading() { + setLoading(true); - } + + loadData(APIUrl).then(setChartData); + }, [APIBaseUrl, accountsId, categoryIds]); /* eslint-disable-next-line react-hooks/exhaustive-deps */ useEffect(updateData, [accountsId]); - useEffect(stopLoading, [chartData]); + + useEffect(() => { + setLoading(!chartData.data); + }, [chartData]); + + useEffect(() => { + const setter = ({accountId}) => setAccountId([accountId]); + + Liferay.on('accountSelected', setter); + + return () => { + Liferay.detach('accountSelected', setter); + }; + }, []); return !accountsId ? (

{Liferay.Language.get('no-account-selected')}