Updating Ref not Triggering Composable Recomputation

365 views Asked by At

I am trying to update a ref object that should trigger the data fetching logic written to return updated data. But this doesn't seem to be working.

App.vue

<script setup lang="ts">
import { ref } from 'vue';
import {usePostData} from './api/usePost.js';

const postToFetch = ref({
  id: 1
})

const onClick = () => {
  postToFetch.value.id++;
}

const { data, isError, isLoading} = usePostData(postToFetch);

</script>

<template>
  <div v-if="isError">Error Fetching Data</div>
  <div v-if="isLoading">Loading</div>
  <div v-if="data">
    <div style="border: 1px dotted green; padding: 10px">
      <pre style="color: red; padding: 2px;">Ref  = {{ postToFetch.id }}</pre>
      <h2>Post Id: {{ data.id }} </h2>
      <h3>Title: {{ data.title }}</h3>
      <p>Content: {{ data.body}}</p>
    </div>
  </div>
  <button @click="onClick">Fetch Next Post</button>
</template>

usePost.js

import { useQuery } from '@tanstack/vue-query'

async function fetchPost(postId) {
    return await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`).then(response => response.json())
}

export function usePostData(postToFetch) { 
  return useQuery({
    queryKey: ['post', postToFetch.value.id],
    queryFn: () => fetchPost(postToFetch.value.id),
    refetchOnWindowFocus: false
  })
}

Ref value is updating but I am not seeing updated post because the usePostData isn't getting triggered. What could I possibly be doing wrong?

Codesandbox

1

There are 1 answers

1
Mohamad Al Omar On

ref used with one value only, and reactive used with objects and lists.

change the ref to reactive will solve your problem.

ref reference: https://vuejs.org/api/reactivity-core.html#ref

reactive reference: https://vuejs.org/api/reactivity-core.html#reactive