mardi 23 mars 2021

Refactoring the if statement for the dates

I was asked to refactor the following:

 if (
                      cell.column.id === 'maintenance_from' ||
                      cell.column.id === 'reg_number_CPDP_date' ||
                      cell.column.id === 'license_date_of_issue'
                    ) {
                      let timestamp = '';
                      Object.keys(cell?.row?.original).forEach(
                        (item: any) => {
                          if (
                            item === 'maintenance_from' ||
                            item === 'reg_number_CPDP_date' ||
                            item === 'license_date_of_issue'
                          ) {
                            timestamp = cell?.row?.original[item];
                          }
                        }
                      );
                      return (
                        <td {...cell.getCellProps()}>
                          {DateParse(timestamp)}
                        </td>
                      );

from the following code:

    import React, { useCallback, useEffect, useState } from 'react';
import { ExtendedTableColumnProps } from 'shared/types/table';
import { useTranslation } from 'react-i18next';
import { Box, Button, Checkbox, Grid, Tooltip } from '@material-ui/core';
import Loader from 'shared/components/Loader/Loader';
import useTranslationRedux from 'shared/hooks/useTranslation';
import { useAsyncFn, useMount } from 'react-use';
import I18nService from 'shared/services/I18nService';
import { PORTAL_BASE_ROUTE } from '../../../shared/navigation/portalRoutes';
import DateParse from '../../../shared/utils/parseDate';

interface TableProps {
  loading?: boolean;
  classes: any;
  instance: any;
  formProps: any;
  setLinkedObjectId?: any;
  type: any;
  selectedLayer: any;
  setFeatureId?: any;
}

const LinkedObjectsFormRowTable: React.FC<TableProps> = ({
  classes,
  instance,
  formProps,
  setLinkedObjectId,
  type,
  loading,
  selectedLayer,
  setFeatureId,
}) => {
  const { t } = useTranslation();
  const [checkboxesState, setCheckboxesState] = useState<any>({});

  const { language } = useTranslationRedux();

  const arrOfNonSpatialData = [
    'logical_networks',
    'buildings',
    'dam_usages',
    'legal_entities',
    'licenses',
    'maintenances',
    'municipalities',
    'water_volumes',
    'water_pump_station_pumps',
    'sewer_pump_station_pumps',
    'irrigate_system_drainage_data',
    'wwtp_data_per_year',
    'water_supply_systems',
    'wastewater_disposal_and_treatment_systems',
    'sewer_networks',
    // 'measurement_devices',
  ];

  const [featuresTranslationsResponse, loadTranslations] = useAsyncFn(
    (layerName: string) => I18nService.layersTransations.getSingle(layerName),
    []
  );

  useMount(() => {
    if (formProps.initialValues.linkedObjectId) {
      setCheckboxesState({
        [formProps.initialValues.linkedObjectId]: true,
      });
    }
  });

  const reloadTranslatons = () => {
    const nonSpatialView = 'view_';

    if (arrOfNonSpatialData.includes(selectedLayer)) {
      loadTranslations(nonSpatialView.concat(selectedLayer));
    } else {
      loadTranslations(selectedLayer);
    }
  };

  useEffect(reloadTranslatons, [language]);

  const featuresTranslations: any =
    featuresTranslationsResponse.value?.data ?? [];

  const translateHeader = useCallback(
    (element: string) => {
      const translation = featuresTranslations?.columns?.find(
        (c: any) => c?.columnKey === element
      );
      return translation?.value.length > 0 ? translation?.value : t(element);
    },
    [featuresTranslations, t]
  );

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement>,
    isNonSpacial: boolean,
    row: any
  ) => {
    const checkBoxVal = Number(e.target.name);

    if (isNonSpacial) {
      Object.keys(row.original).forEach((item: any) => {
        if (item.startsWith('pk') && item.endsWith('id')) {
          if (setLinkedObjectId) {
            setLinkedObjectId(row.original[item]);
          }
          formProps.setFieldValue('linkedObjectId', row.original[item]);
          setCheckboxesState({
            [row.original[item]]: e.target.checked,
          });
        } else if (item.includes('featureId') && setFeatureId) {
          setFeatureId(row.original[item].split('.')[0]);
        }
      });
    } else {
      setCheckboxesState({
        [e.target.name]: e.target.checked,
      });
      if (e.target.checked) {
        formProps.setFieldValue('linkedObjectId', checkBoxVal);
        if (setLinkedObjectId) {
          setLinkedObjectId(checkBoxVal);
        }
      } else {
        formProps.setFieldValue('linkedObjectId', '');
        if (setLinkedObjectId) {
          setLinkedObjectId('');
        }
      }
    }
  };

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    rows,
  } = instance;

  return (
    <Grid item xs={12}>
      {loading ? (
        <Loader text={t('pleaseWait')} isLoading size={100} />
      ) : (
        <Box
          className={classes.featuresTableContainer2}
          style=
          mt={2}
        >
          <Box className="tableScrollContainer" style=>
            <table
              {...getTableProps()}
              cellSpacing={0}
              className={classes.table}
            >
              <thead>
                {headerGroups.map((group: any) => (
                  <tr {...group.getHeaderGroupProps()}>
                    {(group.headers as ExtendedTableColumnProps[]).map(
                      column => {
                        return (
                          <th {...column.getHeaderProps()}>
                            <Box display="flex" alignItems="center">
                              {translateHeader(column.id)}
                            </Box>
                          </th>
                        );
                      }
                    )}
                  </tr>
                ))}
              </thead>
              <tbody {...getTableBodyProps()}>
                {rows.map((row: any) => {
                  prepareRow(row);
                  return (
                    <tr {...row.getRowProps()}>
                      {row.cells.map((cell: any) => {
                        if (/*fkNetworkElId &&*/ cell.column.id === 'choose') {
                          const nameKey: string =
                            Object.keys(cell.row.original).find(
                              key => key.startsWith('pk') && key.endsWith('id')
                            ) || '';
                          const nameValue =
                            type !== 'nonSpatialObjects'
                              ? cell.row.original.fk_network_element_id
                              : cell.row.original[nameKey];
                          return (
                            <td {...cell.getCellProps()}>
                              <Checkbox
                                value={nameValue}
                                checked={checkboxesState[nameValue] || false}
                                onChange={e =>
                                  handleChange(
                                    e,
                                    type === 'nonSpatialObjects',
                                    cell.row
                                  )
                                }
                                name={nameValue}
                              />
                            </td>
                          );
                        }

                        if (
                          cell.column.id === 'options' &&
                          type !== 'nonSpatialObjects'
                        ) {
                          return (
                            <td {...cell.getCellProps()}>
                              <Tooltip title={`${t('linkedObjectsInfo')}`}>
                                <span>
                                  <Button
                                    className={classes.button}
                                    onClick={() => {
                                      const layerName = cell.row.original.featureId.split(
                                        '.'
                                      );
                                      const url = `${PORTAL_BASE_ROUTE}/linked-objects/${cell.row.original.fk_network_element_id}/${layerName[0]}`;
                                      window.open(url, '_blank');
                                    }}
                                  >
                                    <i
                                      className={
                                        'fas fa-external-link-alt fa-lg'
                                      }
                                      style=
                                    />
                                  </Button>
                                </span>
                              </Tooltip>
                              <Tooltip title={`${t('showOnMap')}`}>
                                <span>
                                  <Button
                                    className={classes.button}
                                    onClick={() => {
                                      const layerName = cell.row.original.featureId.split(
                                        '.'
                                      );
                                      const url = `${PORTAL_BASE_ROUTE}?layer=${layerName[0]}&id=${cell.row.original.fk_network_element_id}`;
                                      window.open(url, '_blank');
                                    }}
                                  >
                                    <i
                                      className={'fas fa-map-marked-alt fa-lg'}
                                      style=
                                    />
                                  </Button>
                                </span>
                              </Tooltip>
                            </td>
                          );
                        }

                        if (
                          cell.column.id === 'maintenance_from' ||
                          cell.column.id === 'reg_number_CPDP_date' ||
                          cell.column.id === 'license_date_of_issue'
                        ) {
                          let timestamp = '';
                          Object.keys(cell?.row?.original).forEach(
                            (item: any) => {
                              if (
                                item === 'maintenance_from' ||
                                item === 'reg_number_CPDP_date' ||
                                item === 'license_date_of_issue'
                              ) {
                                timestamp = cell?.row?.original[item];
                              }
                            }
                          );
                          return (
                            <td {...cell.getCellProps()}>
                              {DateParse(timestamp)}
                            </td>
                          );
                        } else {
                          return (
                            <td {...cell.getCellProps()}>
                              {cell.render('Cell')}
                            </td>
                          );
                        }
                      })}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </Box>
        </Box>
      )}
    </Grid>
  );
};

export default LinkedObjectsFormRowTable;

So many question is, how could I please make it this fragment smaller, better? So many question is, how could I please make it this fragment smaller, better? So many question is, how could I please make it this fragment smaller, better? So many question is, how could I please make it this fragment smaller, better? So many question is, how could I please make it this fragment smaller, better? So many question is, how could I please make it this fragment smaller, better?

Aucun commentaire:

Enregistrer un commentaire