SelfTaughtLooking4Job
SelfTaughtLooking4Job

Reputation: 83

How to Set a Fallback Value in React?

I'm making a simple webpage that returns nutrition info for ingredients searched. The data itself is retrieved from an API then pushed into their respective empty arrays (carbs, calories, sodium, etc.) The problem is this API does not return the same array for every single ingredient. For example, it doesn't return fiber for 1 cup of rice. I'm getting errors because the fiber doesn't exist for this ingredient. I'm using react. How can I set a fallback value to make sure I don't get an error in this scenario? I tried the below but it doesn't work.

dietaryFiber = {(totalFiber === undefined) ? 0 : totalFiber}

Edit:

Ok, I think the problem occurs actually in the loop, where searchArray is the input value [[1, cup, rice], [1, whole, apple pie]] for example, and dataArray is the response from this API. It's giving me an error because FIBTG (fiber) doesn't exist when I try to search for rice. What can I do to get around it? Sorry for the ambiguity.

const fiber = []

for(var i=0; i < searchArray.length; i++) {
   fiber.push(dataArray[i].totalNutrients.FIBTG.quantity)
}

Upvotes: 1

Views: 2031

Answers (2)

Rajdeep D
Rajdeep D

Reputation: 3920

You can use either Nullish Coalescing Operator or Ternary operator.

In Ternary operator totalFiber values like null, undefined, 0 will be treated as falsy value

dietaryFiber = totalFiber ? 0 : totalFiber

In Nullish Coalescing operator totalFiber values like null, undefined will be treated as falsy value, 0 will not be treated as falsy value

dietaryFiber = totalFiber ?? 0

You can also use Optional chaining javascript operator to check if any property is undefined and gracefully return undefined without throwing error

dataArray[i].totalNutrients.FIBTG?.quantity ?? 0

Upvotes: 1

user16302651
user16302651

Reputation:

I think:

dietaryFiber = {totalFiber ? 0 : totalFiber}

Upvotes: 0

Related Questions