0

I have a component where I am mapping through an array of items. I am adding a filter to it as well. Right now it looks like this:

{data.products                  
  .filter((item) => item.acf.quiz.gender.some(({ value }) => value === state.theme.quiz.quizGender))
  .map((item, id) => {
    return <ProductCard key={id} item={item} data={data} />;
  })
}

So if the gender has been set to state by a radio button in another component, the map will filter by items where that gender is an attribute. I have that part working just fine.

What I am trying to figure out though, is if there is a way to conditionally apply that filter, so that if the use didn't set their gender, then the filter would not apply. I know there is a way to do this outside of the map, but I am needing to do it inline with this .filter() as there will be several more filters that I will need to apply.

Any help would be great.

1
  • Just have the filter function return true if gender is an empty array. You might also check for undefined. Commented Nov 2, 2020 at 14:19

3 Answers 3

1

So as long as the non selection state is null/undefined/false you can just add a check inside the filter

.filter((item) => 
  !state.theme.quiz.quizGender || 
  item.acf.quiz.gender.some(({ value }) => 
    value === state.theme.quiz.quizGender)
)
Sign up to request clarification or add additional context in comments.

Comments

0

You can apply a check to see if item.acf.quiz.gender has a value, if yes then continue with the operation else, return false

{
  data.products
    .filter((item) =>
      item.acf.quiz.gender
        ? item.acf.quiz.gender.some(
            ({ value }) => value === state.theme.quiz.quizGender
          )
        : false
    )
    .map((item, id) => {
      return <ProductCard key={id} item={item} data={data} />;
    });
}

Comments

0

You just need to return true on the filter if state isn't set :

{
    data.products
        .filter((item) => 
            !state?.theme?.quiz?.quizGender
            || item.acf.quiz.gender.some(({
                    value
                }) => value === state.theme.quiz.quizGender)
        )
        .map((item, id) => {
            return <ProductCard key = {id} item={item} data={data} />;
        })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.