Skip to content
Advertisement

How to use react.usememo using react and javascript?

i am doing some filtering on items based on ids which is in selection object. and then evaluating true or not based on its completion true or false from items which is an array of objects.

below is my code,

const Items: React.FC<RouteComponentProps> = ({history}) => {
    const [{selection}] = tableState;
    const {
        data: items,
        count: itemsCount,
    } = React.useMemo(() => {
        (!isNil(data) ? data.items : { data: [], count: 0}),
        [data]
    );


    let noJobs; 
    if (selection) { //how to put this block in useMemo
        const filteredItems = items.filter(item =>
            Object.keys(selection).includes(item.id)
        );
        noJobs = filteredItems.map(item => item.jobs.map(job => job.completed))
                     .flat().every(Boolean); 
    }


    return (
        <button disabled = {noJobs}> Click me </button>
    );
}

How can i put the block which includes noJobs calcualtion (from if(selection)) to React.useMemo. could someone help me with this. I am learning react and hooks is new to me.

thanks.

Advertisement

Answer

Try followings it:

const Items: React.FC<RouteComponentProps> = ({history}) => {
    const [{selection}] = tableState;
    const {
        data: items,
        count: itemsCount,
    } = React.useMemo(() => {
        (!isNil(data) ? data.items : { data: [], count: 0}),
        [data]
    );


    const noJobs = React.useMemo(() => {
      if (selection) {
        const filteredItems = items.filter(item => {
          return Object.keys(selection).includes(item.id)
        });

        return filteredItems.map(item => item.jobs.map(job => {
          return job.completed
        }))
        .flat()
        .every(Boolean); 
      };

      return undefined; //or everything you want
    } , [items , selection]);

    return (
        <button disabled = {noJobs}> Click me </button>
    );
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement