TanStackT
TanStackโ€ข3y agoโ€ข
24 replies
brilliant-lime

Invalidating query during mutation not working

So, I have a problem I'd like to ask about that is quite elementary. I've built a simple ToDo app on a single page. The problem is I can't get the "invalidateQueries" to work after mutating the data in my database.

Initial list of items:

const getTodos = () => fetch('http://localhost:3000/api/todos').then(response => response.json())

const { isLoading, isError, data, error } = useQuery({
queryKey: ['todos'],
queryFn: getTodos,
})

Mutating the list:

const { mutate } = useMutation({
mutationFn: newTodo =>
useFetch(http://localhost:3000/api/addtodos, {
method: 'post',
body: { newTodo },
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] }) //This isn't working
},
})

As I said, the invalidation doesn't seem to have any effect. The list doesn't update until I click outside the window or wait. However, if I add a plain function triggered by a button I can get the invalidation to work right away:

<button @click="runInvalidate">Invalidate</button>

function runInvalidate() {
queryClient.invalidateQueries({ queryKey: ['todos'] })
}

I posted this the sponsor channel with more of the code and @TkDodo ๐Ÿ”ฎ thought it looked like I'd set things up right.

Thanks for your help!
Was this page helpful?