title: React query mutation typescript
body: <p>I'm just playing around with react-query</p>
  <p>with typescript</p>
  <p>I mean I do my first attempts</p>
  <p>Is it the right way?</p>
  <pre><code>const useCreateTodo = () =&gt; {
    const queryClient = useQueryClient();
    return useMutation(
      (todo: TodoDto) =&gt; axios.post(`${URL}/todos`, todo).then((res) =&gt; res.data),
      {
        onMutate: async (newTodo: TodoDto) =&gt; {
          // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
          await queryClient.cancelQueries(&quot;todos&quot;);
  
          // Snapshot the previous value
          const previousTodos = queryClient.getQueryData(&quot;todos&quot;);
  
          // Optimistically update to the new value
          queryClient.setQueryData&lt;TodoDto[] | undefined&gt;(&quot;todos&quot;, (old) =&gt;
            old ? [...old, newTodo] : old
          );
  
          // Return a context object with the snapshotted value
          return { previousTodos };
        },
        // If the mutation fails, use the context returned from onMutate to roll back
        onError: (
          err,
          newTodo,
          context:
            | {
                previousTodos: unknown;
              }
            | undefined
        ) =&gt; {
          queryClient.setQueryData(
            &quot;todos&quot;,
            context ? context.previousTodos : context
          );
        },
        // Always refetch after error or success:
        onSettled: () =&gt; {
          queryClient.invalidateQueries(&quot;todos&quot;);
        },
      }
    );
  };
  </code></pre>