Prevent reload straight after saving using vue-query and invalidateQueries()

323 views Asked by At

I have this component in Vue. When I save, the server is returning the updated record. So, I don't need to hit the server with yet another request. However, this is triggering the new get:

queryClient.invalidateQueries({ queryKey: ['projects'] })

I am new to vue-query. I realise the cache needs to be invalidated. However... is there any way to prevent another reload when it's invalidated?

<script setup>
import { useDataLoader } from '../lib/dataLoader.js'
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useQuery, useQueryClient, useMutation } from "@tanstack/vue-query";

const route = useRoute()

const api = useDataLoader('projects', { baseUrl: '/stores/1.0.0'})
let record = ref({})

const { isLoading, isFetching, isError, data, error, refetch } = useQuery({
  queryKey: ['projects', route.params.id],
  queryFn: () => api.get(route.params.id).then(data => record.value = data),
})
watch(() => route.params.id, () => { refetch() })

// Access QueryClient instance
const queryClient = useQueryClient()

const mutation = useMutation({
  mutationFn: (record) => api.put(route.params.id, record).then(data => record.value = data),
  onSuccess: (record) => {
    record.value = record
    // Invalidate and refetch
    queryClient.invalidateQueries({ queryKey: ['projects'] })
  },
})

function save (e) {
  const data = Object.fromEntries(new FormData(e.target))
  /* Change data here if necessary */
  mutation.mutate(data)
}

</script>

<template>
<h1>Edit Project</h1>
<form @submit.prevent="save">
  <input name="name" :value="record.name" :id="record.id">
  <input type="submit" value="Save">
</form>

</template>


<style>
</style>
1

There are 1 answers

0
Merc On

Nevermind sorry.

When dealing with mutations that update objects on the server, it's common for the new object to be automatically returned in the response of the mutation. Instead of refetching any queries for that item and wasting a network call for data we already have, we can take advantage of the object returned by the mutation function and update the existing query with the new data immediately using the Query Client's setQueryData method: