1

I'm from Ruby language so sorry for noob question. I've got this response from API:

[{:id=>"61b79d02a0f6af001374744e",
  :name=>"Waffle Crewneck",
  :code=>"FW22KS000",
  :result=>{"status"=>"Success", "message"=>"FW22KS000 - Synced"},
  :last_sync_at=>Wed, 18 May 2022 23:51:45.195079000 UTC +00:00},{:id=>"611ea9a7392ab50013cf4713", :name=>"2-Tone Hoodie", :code=>"SS22CH013", :result=>nil, :last_sync_at=>nil},]

Which I want to display inside of the table:

<tr v-for="product in fetchedProductSyncStatus" :key="product">

<td class="text-bold">
  {{ product.result.status }}
</td>
<td class="text-bold">
  {{ product.result.message }}
</td>
<td class="text-bold">
  {{ product.last_sync_at }}
</tr>

Because in second array element product.result == nil I've got an error:

TypeError: Cannot read properties of null (reading 'status')

Looking for something similar to Ruby's product.result&.message. How to avoid such error in Vue and display empty string instead?

2 Answers 2

4

There's the same thing in TypeScript, called optional chaining. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

{{ product.result?.message }}

Or the old-style product.result && product.result.message

Edit: Optional chaining in templates only works in Vue3

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

2 Comments

Interesting {{ product.result?.message }} crashed the app with an error Uncaught Error: Module build failed (from ./node_modules/vue-loader/lib/loaders/templateLoader.js): but the old-style works well.
Yeah sorry optional chaining in templates is only supported in vue3 (but works in script section)
1

I believe this is more of a javascript rather than Vue issue... you can do something like this to check if product.result is available:

{{product.result ? product.result.status : null}} or

{{ product.result && product.result.status }}

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.