Home > Back-end >  How to wrap the logic inside a react useMemo using react and typescript?
How to wrap the logic inside a react useMemo using react and typescript?

Time:01-25

i want to wrap the logic inside react usememo using typescript and react.

what i am trying to do?

i have an object "filter" and within that there is availableItems which is an array of strings. i want to check if there is two strings "type1" and "type2" within availableItems.

i have a select menu which should be disabled if availableItems is not empty array and availableItems has either type1 or type2

below is the code,

let isSelectDisabled;
if (filter && filter.availableItems) {
    const hasTypes = (filter.availableItems.some((el: any) =>
      ['Type1', 'Type2'].includes(el))
    );
    isSelectDisabled = filter.availableItems.length >= 0 && !hasTypes;
}

return (
    <label>SelectItems</label>
    <Select
        disabled={isSelectDisabled}
    />
);

could someone help me how to wrap above logic in useMemo. thanks.

CodePudding user response:

Pass a function that returns the desired value, and an array of state variables the function depends on to useMemo.

const isSelectDisabled = useMemo(() => {
    if (!filter?.availableItems?.length) return false;
    return !filter.availableItems.some(el => ['Type1', 'Type2'].includes(el));
}, [filter]);

return (
    <label>SelectItems
        <Select disabled={isSelectDisabled} />
    </label>
);

CodePudding user response:

You can try this as a solution. Dependencies may vary according to your requirements

const isSelectDisabled = useMemo(() => {
    if (filter && filter.availableItems) {
        const hasTypes = (filter.availableItems.some((el: any) =>
          ['Type1', 'Type2'].includes(el))
        );
        return filter.availableItems.length >= 0 && !hasTypes;
    }
}, [filter])
  •  Tags:  
  • Related