How to handle missing prismic relational data that website user didn't enter

Hello.

I fetch different data sources in my application which are partly based on each other. Eg I get data1 and then with a value from that data for example data1.title I get another data. But what if the website user doesn't enter data1.title in the backend? I check with v-if of course but I still get a 400 error in the console. The website works fine despite that but I would like to get rid of that error.

Here is an example in Nuxt3:

<script setup>
const route = useRoute();
const name = route.params.uid;
const { client } = usePrismic();
const { data: werk } = await useAsyncData(name, () =>
  client.getByUID("werk", name)
);

const { data: projekt } = await useAsyncData(name + "projekt", () =>
  client.getByUID("projekt", werk.value.data.zugehoriges_projekt.uid)
);
</script>

the data for "werk" always exists but the data for "projekt" might not, if the user hasn't entered it.

That might be more of a nuxt problem but I haven't been able to put an if-condition in script setup which works.

Any ideas?

Hey Tom,

What field type is title in your custom type? If it's a rich text you should extract the text value as plain text before conditionally checking it.

Try something like:

import * as prismicH from '@prismicio/helpers'
// prismicH.asText(projekt.value.data1.title) outputs the rich text as plain text.
if ('value' in projekt && prismicH.asText(projekt.value.data1.title)) {
  ...
}

If you're trying to get a related document from werk instead of relying on a field title/uid you could use relationship field in werk which will give you a document ID for projekt.

// relation is the field name
const { data: projekt } = await useAsyncData(() => client.getByID(werk.value.data.relation.id))
const pageProjekt = projekt.value ? project.value.data : false // or throw helpful error etc.. 

Hope this helps,
Cheers
Jake