Skip to content

Commit

Permalink
LPD-31450 Forecast Chart fixed FE data flow
Browse files Browse the repository at this point in the history
  • Loading branch information
gianmarcobrunialti authored and brianchandotcom committed Jul 14, 2024
1 parent ad63008 commit 7ad7570
Showing 1 changed file with 36 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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 ? (
<p>{Liferay.Language.get('no-account-selected')}</p>
Expand Down

0 comments on commit 7ad7570

Please sign in to comment.