Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

The functionality of the checkbox works perfectly when we do state mutation by {…state}…

  1. User

    The functionality of the checkbox works perfectly when we do state mutation by {…state} import { CreditChargesPaymentTypes, PaymentTableState, initialState } from './paymentTableStateTypes'; import { ModuleState } from '@txp-core/runtime'; import { CHARGES_TABLE_DATA_FETCHED, PaymentChargesTableActionsType, CHARGES_TABLE_DATA_UPDATE, STATE_ID } from './paymentTable_actions'; export interface paymentChargesTableState { paymentChargesTable: PaymentTableState; } const paymentTransactionTable = ( state: paymentChargesTableState = { paymentChargesTable: initialState }, action: PaymentChargesTableActionsType ): paymentChargesTableState => { switch (action.type) { case CHARGES_TABLE_DATA_FETCHED: return { ...state, paymentChargesTable: action.tableData }; case CHARGES_TABLE_DATA_UPDATE: return updateChargesTable(action.txnId, action.payload)(state); default: return state; } }; const updateChargesTable = (txnId: number, payload: Partial) => (state: paymentChargesTableState) => { const newState = { ...state }; const chargesTable = newState.paymentChargesTable.charges; const index = chargesTable.findIndex( (val: CreditChargesPaymentTypes) => val.txnId === txnId ); chargesTable[index] = { ...chargesTable[index], ...payload }; const updatedState = { ...newState, paymentChargesTable: { ...newState.paymentChargesTable, charges: chargesTable } }; console.log('updatedState', updatedState); console.log('state', state); return updatedState; }; export default paymentTransactionTable; export type PaymentChargesTableModuleState = ModuleState<typeof STATE_ID, paymentChargesTableState>; export const paymentTableSelectors = { getCharges: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.charges, getCredits: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.credits, getCustomerBalanceAmount: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.customerBalanceAmount };

    But when we do state mutation by deepclone(state) its breaks import { CreditChargesPaymentTypes, PaymentTableState, initialState } from './paymentTableStateTypes'; import { ModuleState } from '@txp-core/runtime'; import { CHARGES_TABLE_DATA_FETCHED, PaymentChargesTableActionsType, CHARGES_TABLE_DATA_UPDATE, STATE_ID } from './paymentTable_actions'; import { cloneDeep } from '@txp-core/basic-utils'; export interface paymentChargesTableState { paymentChargesTable: PaymentTableState; } const paymentTransactionTable = ( state: paymentChargesTableState = { paymentChargesTable: initialState }, action: PaymentChargesTableActionsType ): paymentChargesTableState => { switch (action.type) { case CHARGES_TABLE_DATA_FETCHED: return { ...state, paymentChargesTable: action.tableData }; case CHARGES_TABLE_DATA_UPDATE: return updateChargesTable(action.txnId, action.payload)(state); default: return state; } }; const updateChargesTable = (txnId: number, payload: Partial) => (state: paymentChargesTableState) => { const newState = cloneDeep(state); const chargesTable = newState.paymentChargesTable.charges; const index = chargesTable.findIndex( (val: CreditChargesPaymentTypes) => val.txnId === txnId ); chargesTable[index] = { ...chargesTable[index], ...payload }; const updatedState = { ...newState, paymentChargesTable: { ...newState.paymentChargesTable, charges: chargesTable } }; console.log('updatedState', updatedState); console.log('state', state); return updatedState; }; export default paymentTransactionTable; export type PaymentChargesTableModuleState = ModuleState<typeof STATE_ID, paymentChargesTableState>; export const paymentTableSelectors = { getCharges: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.charges, getCredits: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.credits, getCustomerBalanceAmount: (state: PaymentChargesTableModuleState) => state?.[STATE_ID]?.paymentChargesTable?.customerBalanceAmount };

    import React, { useState } from 'react'; import { ChargesTable, paymentTableSelectors, PaymentChargesTableAction } from '@txp-core/payment-transactions-table'; import { Table } from '@ids-ts/table'; import { useTXPStateRead, useTXPStateWrite } from '@txp-core/runtime'; import { useFormatMessage } from '@txp-core/intl'; import { TransactionActions, TransactionSelectors } from '@txp-core/transactions-core'; import TextField from '@ids-ts/text-field'; import { enabled } from '@txp-core/enabled'; import { TransactionTypes, getTxnUrl } from '@txp-core/transactions-utils'; import { toLocalizedMoneyString, toLocalDateFormat } from '@txp-core/basic-utils'; import TransactionsTableHeader from './TransactionTableHeaders'; import styles from 'src/js/staticLayout/Grid.module.css'; import Checkbox from '@ids-ts/checkbox'; import style from './Tables.module.css'; import { useTrowserHooks } from '@txp-core/trowser'; import LinkButton from '@txp-core/link-button'; export interface txnType { txnTypeId: number; txnTypeLongName: string; } export interface OutstandingTableDataTypes { txnId: number; txnType: txnType; date: string; amount: string; referenceNumber: number; dueDate: string; openBalance: string; linkedPaymentAmount: string; isLinkedPaymentAmount?: boolean; } export const OutstandingTransactionsTable = () => { const formatMessage = useFormatMessage(); const customerId = useTXPStateRead(TransactionSelectors.getContactId); const outstandingTableLines = useTXPStateRead(paymentTableSelectors.getCharges) || []; const onAmountFieldUpdated = useTXPStateWrite(TransactionActions.genericTxnUpdate); const onPaymentFieldUpdated = useTXPStateWrite( PaymentChargesTableAction.chargesTableDataUpdate ); const Items = (props: { item: OutstandingTableDataTypes; idx: number }) => { const { item, idx } = props; console.log('hello', item, idx); const txnUrl = getTxnUrl(${item.txnType.txnTypeId}, item.txnId); const referenceNumber = item?.referenceNumber ? # ${item?.referenceNumber} : ''; const amount = useTXPStateRead(TransactionSelectors.getAmount) || 0; const { closeTrowser } = useTrowserHooks(); const [isCheckedWhenPaymentAmount, setIsCheckedWhenPaymentAmount] = useState( !!item.linkedPaymentAmount ); console.log('hello2', isCheckedWhenPaymentAmount); const [paymentAmount, setPaymentAmount] = useState(item.linkedPaymentAmount); console.log('hello3', paymentAmount); const handleAmountUpdate = (amountValue: string) => { onAmountFieldUpdated({ amount: amountValue }); }; const handleCheckboxClicked = (txnId: number) => { setIsCheckedWhenPaymentAmount(!isCheckedWhenPaymentAmount); console.log('hello4', isCheckedWhenPaymentAmount, !isCheckedWhenPaymentAmount); if (!isCheckedWhenPaymentAmount) { const value = outstandingTableLines.filter((x) => x.txnId === txnId)[0].openBalance; setPaymentAmount(value.toString()); console.log('hello8', paymentAmount); const calcAmount = Number(amount) + Number(value); handleAmountUpdate(calcAmount.toString()); onPaymentFieldUpdated(txnId, { linkedPaymentAmount: value.toString(), isLinkedPaymentAmount: true }); } else { setPaymentAmount(''); const value1 = outstandingTableLines.filter((x) => x.txnId === txnId)[0] .isLinkedPaymentAmount; console.log('123', value1); if (value1) { const value = outstandingTableLines.filter((x) => x.txnId === txnId)[0] .linkedPaymentAmount; if (value) { const calcAmount = Number(amount) - Number(value); handleAmountUpdate(calcAmount.toString()); onPaymentFieldUpdated(txnId, { linkedPaymentAmount: '' }); } } } }; const handlePaymentFieldChange = (evt: React.ChangeEvent) => { const value = evt && evt.target.value; setPaymentAmount(value); }; const handlePaymentOnBlur = () => { setIsCheckedWhenPaymentAmount(!!paymentAmount); const oldValue = outstandingTableLines.filter((x) => x.txnId === item.txnId)[0] .linkedPaymentAmount; onPaymentFieldUpdated(item.txnId, { linkedPaymentAmount: paymentAmount, isLinkedPaymentAmount: true }); const oldPaymentAmount = oldValue ? Number(oldValue) : 0; const newPaymentAmount = paymentAmount ? Number(paymentAmount) : 0; const calcAmount = Number(amount) - oldPaymentAmount + newPaymentAmount; handleAmountUpdate(calcAmount.toString()); }; const handleNavigate = () => closeTrowser?.({ navigateTo: txnUrl, skipTrowserCloseDelay: true }); return ( <> <Table.Row key={idx} className='tableRow'> <Table.Cell className={style.checkbox}> <Checkbox aria-label={formatMessage({ id: 'charges_credits_table_select_rows', defaultMessage: 'Select rows' })} style={{ cursor: 'pointer' }} checked={isCheckedWhenPaymentAmount} onClick={() => handleCheckboxClicked(item.txnId)} title='Toggle Row Selected' /> </Table.Cell> <Table.Cell className={styles.leftAlign}> <LinkButton onClick={handleNavigate} text={${item.txnType.txnTypeLongName} ${referenceNumber}} />{' '} ({toLocalDateFormat(item.date)}) </Table.Cell> <Table.Cell className={styles.leftAlign}> {toLocalDateFormat(item.dueDate)} </Table.Cell> <Table.Cell className={styles.rightAlign}> {toLocalizedMoneyString(item.amount)} </Table.Cell> <Table.Cell className={styles.rightAlign}> {toLocalizedMoneyString(item.openBalance)} </Table.Cell> <Table.Cell> <TextField autoComplete='off' value={paymentAmount} aria-label={formatMessage({ id: 'charges_credits_payment_field', defaultMessage: 'Payments' })} className={styles.paymentField} onChange={handlePaymentFieldChange} onBlur={handlePaymentOnBlur} /> </Table.Cell> </Table.Row> </> ); }; return ( {customerId && ( <ChargesTable header={}> {(item: OutstandingTableDataTypes, idx: number) => ( )} )} ); }; export default enabled( { 'environment.txnType': [TransactionTypes.PURCHASE_BILL_PAYMENT] }, OutstandingTransactionsTable );

    In this code what is happening that when we click the checkbox the amount add eg amount =5 but the ui checkbox is not getting checked on first click, then if we click the check box for 2nd time then it gets checked and amount gets added eg now amount will be eg amount=10, then after if uncheck the checkbox it doesn’t unchecked it for first time but amount get subtract eg now amount=5,then after we uncheck the checkbox 2nd time it gets unchecked, but the amount remains same eg amount=5, please find issue and solve it

  2. Assistant

    The issue seems to lie in the handleCheckboxClicked function. The handleCheckboxClicked function sets the state with setIsCheckedWhenPaymentAmount using a callback function, but it then tries to immediately access that updated state value. The issue here is that the state updates in React are asynchronous, which means that the value of the state might not be immediately updated after calling setState.

    A possible solution would be to use a temporary local variable to store the updated checkbox state before using it to perform the necessary actions. Here's the updated handleCheckboxClicked function:

    const handleCheckboxClicked = (txnId) => {
      const updatedIsChecked = !isCheckedWhenPaymentAmount;
      setIsCheckedWhenPaymentAmount(updatedIsChecked);
    
      console.log('hello4', isCheckedWhenPaymentAmount, updatedIsChecked);
    
      if (!updatedIsChecked) {
        const value = outstandingTableLines
          .filter((x) => x.txnId === txnId)[0]
          .openBalance;
        setPaymentAmount(value.toString());
        console.log('hello8', paymentAmount);
    
        const calcAmount = Number(amount) + Number(value);
        handleAmountUpdate(calcAmount.toString());
        onPaymentFieldUpdated(txnId, {
          linkedPaymentAmount: value.toString(),
          isLinkedPaymentAmount: true,
        });
      } else {
        setPaymentAmount('');
        const value1 = outstandingTableLines
          .filter((x) => x.txnId === txnId)[0]
          .isLinkedPaymentAmount;
        console.log('123', value1);
    
        if (value1) {
          const value = outstandingTableLines
            .filter((x) => x.txnId === txnId)[0]
            .linkedPaymentAmount;
          if (value) {
            const calcAmount = Number(amount) - Number(value);
            handleAmountUpdate(calcAmount.toString());
            onPaymentFieldUpdated(txnId, {
              linkedPaymentAmount: '',
            });
          }
        }
      }
    };
    

    This change should fix the issue you're experiencing with the checkbox not behaving as expected on the first click. The updatedIsChecked variable allows you to use the updated checkbox state, which resolves part of the problem.

    Please try implementing this solution and let me know if it successfully addresses the issue.

  3. User

    by above checkbox is checking and unchekcing correctly,but the amount and payment amount is not updating

  4. Assistant

    I apologize for the confusion. In that case, let's also make sure that the paymentAmount value is being updated with the latest value while updating the state.

    Please update the handleCheckboxClicked function as follows:

    const handleCheckboxClicked = (txnId) => {
      const updatedIsChecked = !isCheckedWhenPaymentAmount;
      setIsCheckedWhenPaymentAmount(updatedIsChecked);
    
      console.log('hello4', isCheckedWhenPaymentAmount, updatedIsChecked);
    
      if (!updatedIsChecked) {
        const value = outstandingTableLines
          .filter((x) => x.txnId === txnId)[0]
          .openBalance;
        const updatedPaymentAmount = value.toString();
        setPaymentAmount(updatedPaymentAmount);
        console.log('hello8', updatedPaymentAmount);
    
        const calcAmount = Number(amount) + Number(value);
        handleAmountUpdate(calcAmount.toString());
        onPaymentFieldUpdated(txnId, {
          linkedPaymentAmount: updatedPaymentAmount,
          isLinkedPaymentAmount: true,
        });
      } else {
        const updatedPaymentAmount = '';
        setPaymentAmount(updatedPaymentAmount);
        const value1 = outstandingTableLines
          .filter((x) => x.txnId === txnId)[0]
          .isLinkedPaymentAmount;
        console.log('123', value1);
    
        if (value1) {
          const value = outstandingTableLines
            .filter((x) => x.txnId === txnId)[0]
            .linkedPaymentAmount;
          if (value) {
            const calcAmount = Number(amount) - Number(value);
            handleAmountUpdate(calcAmount.toString());
            onPaymentFieldUpdated(txnId, {
              linkedPaymentAmount: updatedPaymentAmount,
            });
          }
        }
      }
    };
    

    I have added the updatedPaymentAmount variable, which holds the latest value for the payment amount at each step, similarly to the way we used the updatedIsChecked variable for the checkbox state.

    This should fix the issue with the amount and payment amount not updating correctly. Please give it a try and let me know if it resolves the issue.