NuxtN
Nuxt10mo ago
18 replies
hackal

useFetch not updating data ref when new request is triggered.

This is my simplified version of composable
const projectCache = () => useState("projectCache", () => ref({}))

const useProject = async (projectId: Ref<string>) => {
  const localId = ref(unref(projectId));

  watch(projectId, (newId) => {
    if (projectCache().value[newId]) {
      // project already in cache, we can set localId immediately
      localId.value = newId;
    }
  })

  const {
    data,
    execute,
  } = useFetch(() => `/my/url/${projectId}`, { immediate: false })

  watch(data, (updated) => {
    // new data from api, update cache and set the ID
    projectCache().value[data.value.id] = data.value;
    localId.value = data.value.id;
  })

  // check if we have project in cache
  if (!projectCache().value[unref(projectId)]) {
    // cache miss, we make the request and save to cache
    await execute();
    if (data.value) {
      // add/update data in cache
      projectCache().value[data.value.id] = data.value
    }
  }

  return {
    // always return from cache
    project: computed(() => projectCache().value[unref(localId)])
  }
}


I have the following issue. I call the composable in two components and pass the same id (ref) as arg const { data } = await useProject(projectId) when the projectId changes I see that useFetch will fire two requests however watch(data, (updated) => { is called only in one instance. Why that could be?
Was this page helpful?