N
Nuxt5mo ago
pano9000

Conditional useFetch?

Hi All, I am new to Nuxt (so this might sound like a stupid question): But is it possible to conditionally call useFetch in the script setup? What I am trying to achieve: I have a cookie, that contains two values (streetname & streetno). This cookie is also reactive, i.e. users have the possibility to change these values while on the page, which then gets stored in the cookie again. For a new page visitor these values default to an empty string "", for recurring visitors, the values are valid strings. These values are to be used as query params for an internal Nuxt API call, and should retrigger a fetch, when the values change. This seems to be working correctly as well so far. HOWEVER I would like to prevent useFetch from making useless fetch attempts, when the values are empty (or 'falsy' in general) - and this is where I get confused on how to achieve that. This is my current code (which still lacks a bit of fetch error handling, but let's ignore that for now):
<script setup lang="ts">
import type { myApiResponseType } from "~/server/services/MyApiService.js"
import { userCookieUserConfig } from "~/components/useCookieUserConfig";

const { cookieStreet } = userCookieUserConfig();
const streetname = toRef(() => cookieStreet.value.streetname);
const streetno = toRef(() => cookieStreet.value.streetno);
const hasStreet = computed( () => !!cookieStreet.value.streetname && !!cookieStreet.value.streetno);

//const apiData = ref<myApiResponseType |null>(null)

const apiUpcoming = await useFetch<myApiResponseType >("/api/v1/upcoming", {
query: {
streetname: streetname,
streetno: streetno
}
});


</script>
<script setup lang="ts">
import type { myApiResponseType } from "~/server/services/MyApiService.js"
import { userCookieUserConfig } from "~/components/useCookieUserConfig";

const { cookieStreet } = userCookieUserConfig();
const streetname = toRef(() => cookieStreet.value.streetname);
const streetno = toRef(() => cookieStreet.value.streetno);
const hasStreet = computed( () => !!cookieStreet.value.streetname && !!cookieStreet.value.streetno);

//const apiData = ref<myApiResponseType |null>(null)

const apiUpcoming = await useFetch<myApiResponseType >("/api/v1/upcoming", {
query: {
streetname: streetname,
streetno: streetno
}
});


</script>
If I wrap the useFetch call in a conditional, e.g. checking if "hasStreet" is true -> I seem to lose the initial SSR fetching, which I'd like to avoid as well, if possible. Anyone with an idea if that is possible? Thanks in advance!
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server