Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine custom hooks and selector results?

I have a custom hook and also have some selectors and need a final flag to be set based on a combination of the two. I can't simply write a function that combines the code below cos neither hooks or selectors can be used outside a react FC

What's the best way to make the whole block like this a single reusable function somewhere?

// selector
    const { activeIntents, writeRole, intents, permalink } = useSelector(state => state.companyIntentsReducer);
// custom hook
    const { hasExtendedRoleForCompany } = useJwtRoles();
// func calling the custom hook
    const intentWrite = hasExtendedRoleForCompany("intent-manage-write", permalink);
// final result combines both
    const editMode = writeRole && intentWrite

can custom hooks use selectors?

like image 224
dcsan Avatar asked Oct 25 '25 22:10

dcsan


1 Answers

You should write a custom hook, something like:

const useEditMode = () => {
  const { activeIntents, writeRole, intents, permalink } = useSelector(
    (state) => state.companyIntentsReducer
  );

  const { hasExtendedRoleForCompany } = useJwtRoles();
  const intentWrite = hasExtendedRoleForCompany(
    "intent-manage-write",
    permalink
  );

  return { isEditMode: writeRole && intentWrite };
};

export default useEditMode;

// Usage inside function component
const { isEditMode } = useEditMode();
like image 61
Dennis Vash Avatar answered Oct 27 '25 10:10

Dennis Vash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!