`useQueryClient()` from `react-query` not working in the separated `mutationFn` causing function inexecution

70 Views Asked by At

I'm trying to separate the mutationFn from the useMutation() so that the code would be a bit easier to read.

However, it turns out that the useQueryClient() doesn't seem to work outside the useDeleteAllTasks() hook function. I'd like to know why that is the case, and how I could possibly separate the function and still get it to work as I first intended it to.

The backend being used is the JSON Server. Fetching with React Query V5 & Axios.

So here is the code in the useDeleteAllTasks() hook, which works perfectly as intended:

export const useDeleteAllTasks = () => {
    const currentQuery = useQueryClient()

    return useMutation({
        mutationKey: ['delete-all-tasks'],
        mutationFn: () => {
           const prevTasks = currentQuery.getQueryData<Task[]>(['tasks'])
           const taskArray = prevTasks?.map(task => task.id);
           taskArray?.forEach(id => deleteTaskByID(id))
        },
        onSettled: () => currentQuery.invalidateQueries({ queryKey: ['tasks'] })
    })
}

But I thought this would also work, but doesn't:

export const useDeleteAllTasks = () => {
    const currentQuery = useQueryClient()

    return useMutation({
        mutationKey: ['delete-all-tasks'],
        mutationFn: deleteAllTasks
        },
        onSettled: () => currentQuery.invalidateQueries({ queryKey: ['tasks'] })
    })
}


const deleteAllTasks = () => {
    
    // This logs as expected
    console.log('deleteAllTasks() - 1')

    // This line does NOT seem work, which causes the rest of the function to stop working.
    const currentQuery = useQueryClient()

    // This doesn't show up at all
    console.log('deleteAllTasks() - 2')

    // No response from the function beyond this line
    const prevTasks = currentQuery.getQueryData<Task[]>(['tasks'])
    const taskArray = prevTasks?.map(task => task.id);
    taskArray?.forEach(id => deleteTaskByID(id))

    console.log('deleteAllTasks() - DONE')
}

All productive suggestions are welcome :)

0

There are 0 best solutions below