0

I've got a list of products to render. I also have an array of keywords that are used to exclude products from being rendered.

I am looping over the array of keywords and checking if the product title contains any of the entries. It then returns a boolean.

The following code does not work. The console.log works and reflects the result but nothing is rendered.

function inExcludes(product, excludedItems) {

  excludedItems.forEach( item => {
    if (product.includes(item)) {
      console.log(true);
      return true;
    } else {
      console.log(false);
      return false;
    }
  })
  
}
export function CardsFiltered(props) {

  const cards = props.items.map((product) => {
    if (inExcludes(product.title, props.excludedItems) === false)
    return (
      <CardValidation
        key={product.id}
        id={product.id}
        product={product}
      />
    )
  })

  return (
    <>
      {cards}
    </>
  );

}

But if I set a variable as a boolean, switch that variable if the condition is true, and then return that variable, it works and my cards are rendered (code below).

Is anyone able to shed light on this? Because I can't figure it out.

function inExcludes(product, excludedItems) {
  let result = false;

  excludedItems.forEach( item => {
    if (product.includes(item)) {
      result = true;
    }
  })

  return result;
}
export function CardsFiltered(props) {

  const cards = props.items.map((product) => {
    if (!inExcludes(product.title, props.excludedItems))
    return (
      <CardValidation
        key={product.id}
        id={product.id}
        product={product}
      />
    )
  })

  return (
    <>
      {cards}
    </>
  );

}
ComicDansMS
  • 31
  • 1
  • 5
  • Please read up on how forEach works. It doesn't work like your basic `for loop`. Read this QnA - https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function – Vishal Dhawan May 22 '22 at 07:25

1 Answers1

0

Your first implementation of 'inExcludes' isn't returning a boolean (true/false). It's just executing the 'forEach' on each item in the excludedItems array. The return within that loop doesn't return from the function as a whole.

So, as it effectively returns 'undefined' your render decides not to render anything.

Here's something that does what you're after (simplified a bit):

https://codesandbox.io/s/awesome-mcclintock-hkkhsi?file=/src/App.js

Mark Williams
  • 2,268
  • 1
  • 11
  • 14
  • Ah! Of course. Thanks for the code. I'm needing to check if the product title contains a keyword (hence using string.includes()), but your answer and Vishal's comment have pointed me in the right direction and it's solved the issue. Thanks! – ComicDansMS May 22 '22 at 08:06
  • Thanks @ComicDansMS, good luck with everything. – Mark Williams May 22 '22 at 08:11