How to use useSelector inside tableUtils.jsx

120 Views Asked by At

I couldn't able to use useSelector inside tableUtils.jsx file.

Tried accessing state value but end up in error.React Hook "useSelector" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function.

export const userDetails = useSelector((state) => state?.user?.userDetails);

This is how my utils.jsx files looks like

import { UserFilled, TrashCan } from '@carbon/icons-react';
const generateActionColumn = (item, deactivateStatus, auditTrialModal, classNames, deleteUser, onClickSendReminder) => (
  <div className="actionColumn" title={i18n.t('icons.rerenderUser')}>
    {item.status === classNames.invitedStatus ? (
      <Resend className="email" onClick={() => onClickSendReminder(item, true)} />
    ) : (
      <Resend className="email" style={{ visibility: 'hidden' }} />
    )}
    <span title={i18n.t('icons.deleteUser')}>
      <TrashCan className="delete icon_delete_user" onClick={() => deleteUser(item, true)} />
    </span>
    <OverflowMenu aria-label="overflow-menu" title={i18n.t('button.moreOptions')} flipped className="overflowMenuContainer">
      <OverflowMenuItem
        className={`tableDactivateButton ${
          item.status === classNames.registeredStatus
            ? classNames.deactiveClassname
            : item.status === classNames.deactivatedStatus
            ? classNames.activeClassname
            : ''
        }`}
        itemText={item.status === classNames.deactivatedStatus ? classNames.activateText : classNames.deactivateText}
        onClick={() => deactivateStatus(item, true)}
      />
      <OverflowMenuItem itemText={i18n.t('button.auditTrial')} onClick={() => auditTrialModal(item, true)} />
    </OverflowMenu>
  </div>
);

Want to use state value inside tableUtils.jsx (non react component)

1

There are 1 best solutions below

10
Gavara.Suneel On

Yes. You can not use the hooks outside a functional component. So that's why it is throwing the error. If you want to reuse the logic across different components, I suggest creating a custom hook.

const useTableUtils = () => { 
 const userDetails = useSelector((state) => state?.user?.userDetails);
 return {
       userDetails
   }
}

Inside the component use it like below

import {useTableUtils} from 'PATH_TO_ABOVE_FILE'

function YOUR_FUNCTIONAL_COMPONENT {

const { userDetails } = useTableUtils()

// Use the userDetails as you required 
}

You can re-use the above custom hook in other components as well.