ousmane784
ousmane784

Reputation: 446

JS only execute if statement based on condition

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"]

Upvotes: 0

Views: 67

Answers (3)

Rajesh
Rajesh

Reputation: 24915

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

Upvotes: 1

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11905

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.

Upvotes: 2

SARAN SURYA
SARAN SURYA

Reputation: 554

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 :)

Upvotes: 1

Related Questions