1

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

2
  • 1
    The sandbox is unavailable. The problem is likely useQuery receives just a value, it cannot be reactive. Providing too much data (postToFetch) is design mistake any way. Make id a ref and pass it like queryKey: ['post', id], this is what refs are for, to pass a value by reference Commented Sep 5, 2023 at 11:58
  • @EstusFlask passing the ref & not unpacking it while setting the queryKey solved the issue. I got your point about the design mistake to pass too much data! Sandbox is updated Commented Sep 6, 2023 at 18:06

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is incorrect, you describe the behaviour of shallowRef, regular ref is deeply reactive

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.