7Stuffs
7Stuffs

Reputation: 85

ReactJS Find Array Prevent Return Undefined

I want to get the brandName inside the brandData
But when the productBrandID isn't available in the brandData, it returned undefined
I don't want this happened, i want it return a value like --- Select Brand --- or what

              <select className="form-control" id="productBrand" name="productBrand" value={productForm.productBrand} onChange={(e) => handleOnChange(e)}>
                <option value={productForm.productBrandID}>
                  {productForm.productBrandID ? brandData.find(brand => brand.id === productForm.productBrandID).brandName : '--- Select Brand ---'}
                </option>
              </select>

Upvotes: 0

Views: 181

Answers (2)

Chuck
Chuck

Reputation: 804

Well, I am not 100% sure about this, but worthy try.

 {productForm.productBrandID ? brandData.find(brand => brand.id === productForm.productBrandID).brandName || '--- Select Brand ---' : '--- Select Brand ---'}

Upvotes: 0

David
David

Reputation: 218818

First, handle the case where .find() doesn't find a match. You can use optional chaining for that:

brandData.find(brand => brand.id === productForm.productBrandID)?.brandName

Second, now that this can safely return no value (instead of throwing an error) then you can use the nullish coalescing operator to supply a default value:

brandData.find(brand => brand.id === productForm.productBrandID)?.brandName ?? '--- Select Brand ---'

Once you have that, determine if the logic you already have is valid at all. Will productForm.productBrandID ever be null or undefined? And if it is, will any brandData record have a null or undefined value for its id? I wouldn't expect so, so this new logic can probably entirely replace the logic you have:

<option value={productForm.productBrandID}>
  {brandData.find(brand => brand.id === productForm.productBrandID)?.brandName ?? '--- Select Brand ---'}
</option>

Upvotes: 2

Related Questions