react-query icon indicating copy to clipboard operation
react-query copied to clipboard

Examples for mutations, queryClient?

Open fholmqvist opened this issue 2 years ago • 3 comments

Would it be possible to pad out the examples with mutations and their callbacks? I've been wrestling ReactQuery.useMutation({onSuccess: ...}) with queryClient (getQueryData, setQueryData etc) but failing to wrap my head around it.

QueryClient is listed as work in progress, but current version is 1.1.0. Can it be used?

fholmqvist avatar Oct 10 '23 12:10 fholmqvist

Hey @Holmqvist1990 👋 Could you elaborate about your need? I'm not working on this repo actively, but I have plans to finish the support for the missing bindings.

vmarcosp avatar Oct 10 '23 22:10 vmarcosp

Hey @vmarcosp, thanks for the reply! :wave:

The README demonstrates:

let queryResult = ReactQuery.useQuery({
      queryFn: fetchTodos,
      queryKey: ["todos"],
      /*
       * Helper functions to convert unsupported TypeScript types in ReScript
       * Check out the module ReactQuery_Utils.res
       */
      refetchOnWindowFocus: ReactQuery.refetchOnWindowFocus(#bool(false)),
    })

Perhaps it could also demonstrate something like:

let queryClient = ReactQuery.useQueryClient()

let addTodoMutation = ReactQuery.useMutation({
    mutationFn: addTodo,
    mutationKey: ["todos"],
    onSuccess: (todo: todo) => {
        queryClient.setQueryData(["todos"], (oldTodos) => Js.Array2.append(oldTodos, todo))
    
        // or
    
        let todos: array<todo> = queryClient.getQueryData(["todos"])->Option.getWithDefault([])
        todos->Array.push(todo)
        queryClient.setQueryData(["todos"], Some(todos))
    }
})

(note: above examples don't compile)

fholmqvist avatar Oct 11 '23 06:10 fholmqvist

What error are you getting with this code? setQueryData is typed as ('queryKey, option<'queryData>) => unit which assumes the use as setQueryData(["todos"], newTodo), it's possible to support setQueryData as ('queryKey, option<'queryData> => queryData as well (using the updater function) but I think you can still do the same since you can get the same value by doing queryClient.getQueryData with the same queryKey.

vmarcosp avatar Oct 15 '23 22:10 vmarcosp