I want to get some data from HTTP API and display it on the page:
<template>
<div>
Kyiv Time: {{ timeData.utc_datetime }}
</div>
</template>
<script setup>
const { data: timeData } = await useFetch('https://worldtimeapi.org/api/timezone/Europe/Kiev')
</script>
Sometimes page loads correctly, and sometimes I got an error Cannot read properties of null (reading 'utc_datetime')
in the template. So await doesn't really wait for the HTTP request.
How can I wait for HTTP request during SSR (and client-side as well)?
My nuxt config is empty, here the project sources
You should check not only data
but also error
. If an error occurred while fetching (e.g. timeout), data
will be null
.
You can either handle this in your template:
<div v-if="data">
...
</div>
<div v-else>
...
</div>
or throw an error in script:
if (error.value) {
throw createError(...)
}