0

I am fetching data from an api and I need to render a component based on an if statement and I cant seem to figure it out. A customer has an array of roles. Customer.items is an array of customer objects. This is the if statement I am trying but doesnt work:

{customers?.items?.length > 1 && !roles.includes("Super") && (...component

Basically I need to check if roles array has "Super" and customers.items only has one element then dont render the component.

Also if roles is "Super" and customer.items.length > 1 then still render the component

customers.items: [{id: 2, name: "G"}, {id: 3, name: "H"}]
roles: ["Super", "Admin"]
2
  • Please give a sample snippet of your customers object and roles array Commented Feb 4, 2021 at 4:36
  • I added an edit Commented Feb 4, 2021 at 4:40

3 Answers 3

2

This will render the component in all cases except when customers.items has only one element and if the roles include 'Super'.

const hasSingleCustomer = customers?.items?.length === 1
const hasSuperRole = roles.includes('Super'))


{!(hasSingleCustomer && hasSuperRole) && <Component />}

You can also write it as {(!hasSingleCustomer || !hasSuperRole) && <Component />} if you prefer.

Sign up to request clarification or add additional context in comments.

6 Comments

Maybe I worded it weirdly but the only condition when the component should NOT render is when the role is super and customer.items.length === 1
If role is "Admin" it doesnt matter what the length is, still render component
@ousmane784 Ah, got it. Let me update my answer.
Sorry, If role is "Admin" and customer.items.length === 0 the component should still render
@ousmane784, please list down all conditions in your question
|
1

You can try this approach

{(customers.items.length > 1 && roles.includes("Super")) ? <If Success Component/> : <Failure Component>}

I have written as per your request, as I am checking if the roles array has "Super" in it, You can still manipulate the operation inside the brackets(), and we have to use ? and : to make sure the conditions work,

Happy Coding :)

Comments

1

My suggestion is to split the equation/ conditions into smaller variables and then use them to create a validity condition. This way, your code is more readable and easier to maintain

const length = customers.items.length
const isSuperUser = roles.includes('Super')
const isAdminUser = roles.includes('Admin')
const isAllowedForSuper = isSuperUser && length === 1
const isAllowedForAdmin = isAdminUser && length === 0

if (isAllowedForSuper || isAllowedForAdmin) {
  return <Component {...props} />
}
return null

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.