Search code examples
reactjsreduxredux-toolkitrtk-query

isSuccess for mutations in RTK Query


I'm calling the mutation method as usual,

const [addTodo] = useAddTodoMutation();

So we have options like isLoading,isSuccess,isError,error from a query builder (From GET requests). But Can't we have the same options with mutations too?


Solution

  • It's already there :)

    For query hooks, the return value is an object containing data and the various loading/status flags: const { data, isFetching} = useSomeQuery().

    For mutation hooks, the return value is a tuple containing the "trigger" function as the first entry, and an object containing the status flags as the second entry: const [trigger, objectWithStatusFlags] = useSomeMutation():

    So, just extract that object (and optionally destructure the fields from it):

    // Either this:
    const [addTodo, mutationFlags] = useAddTodoMutation();
    
    // or this:
    const [addTodo, {isLoading}] = useAddTodoMutation();