N
Nuxt7mo ago
plex

Reactivity on rendered elements?

I'm using Apollo to fetch an object from my API. The response is passed to a ref variable. Now I want a button to be rendered differently depending on the value of the ref. This does not work on SSR, as the element does not change after the initial render, although the ref value did. Example:
<script setup>
const { result, loading } = useQuery(getLike);

const liked = ref(result?.value?.like || false);
</script>

<template
<UButton :icon="liked ? 'i-mdi-heart' : 'i-mdi-heart-outline' />
<div :class="liked ? 'bg-green' : 'bg-red'>
{{ liked }}
</div>
</template>
<script setup>
const { result, loading } = useQuery(getLike);

const liked = ref(result?.value?.like || false);
</script>

<template
<UButton :icon="liked ? 'i-mdi-heart' : 'i-mdi-heart-outline' />
<div :class="liked ? 'bg-green' : 'bg-red'>
{{ liked }}
</div>
</template>
After a reload, neither the button nor the div are rendered accordingly in this case, they stay at i-mdi-heart-outline and bg-red, although the variable text of "liked" is displayed correctly. I've tried different things, like using a computed property or setting the initial value to null but nothing helps. Note that I don't want to use an async query in this case to avoid delays when loading the page.
2 Replies
Likonima
Likonima7mo ago
I dont quite understand what you're doing but the ref wont be reacting to result changes
plex
plex7mo ago
The value itself is reacting though, the {{ liked }} part in the template is changing accordingly to the result.
Want results from more Discord servers?
Add your server