← Back to React Course | Chapter 10: Data Fetching & Async | Lesson 6 of 10

React Query से Mutations

React Query में एक mutation librarian को एक change request भेजने जैसा है, जो फिर अपने records update कर देता है ताकि हर कोई latest version देखे।
Syntax
markup
const queryClient = useQueryClient();

const mutation = useMutation({
  mutationFn: mutationFunction,
  onSuccess: () => queryClient.invalidateQueries({ queryKey: ["key"] }),
});

mutation.mutate(variables);

Mutations किसलिए हैं

जबकि useQuery data पढ़ना handle करता है, useMutation इसे लिखना handle करता है — server पर कुछ create, update, या delete करना। यह एक mutationFn (actual API call) और एक mutate function के around बना है जिसे आप भेजने वाले data के साथ call करते हैं।

Note: useQuery को GET requests और useMutation को POST/PUT/DELETE requests की तरह सोचें।
Warning: Queries की तरह Mutations render पर automatically नहीं चलते — आप इन्हें हमेशा explicitly trigger करते हैं, आमतौर पर एक event handler से।

उदाहरण: What Mutations Are For

markup
// Run in your local React project (npm install required)
import { useMutation } from '@tanstack/react-query';

function AddUserForm() {
  const mutation = useMutation({
    mutationFn: newUser => fetch('/api/users', { method: 'POST', body: JSON.stringify(newUser) }),
  });
  return <button onClick={() => mutation.mutate({ name: 'Asha' })}>Add User</button>;
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Mutation के बाद Related Data को Refresh करना

कुछ successfully add, update, या delete करने के बाद, related list (जैसे [users]) के लिए cached query अब stale है। Mutation के onSuccess callback में queryClient.invalidateQueries call करना React Query को उस query refetch करने को कहता है, UI को server से sync रखते हुए।

Note: जो बदला उससे related specific query key invalidate करें, सब कुछ invalidate करने के बजाय, unnecessary refetches से बचने के लिए।
Warning: Mutation के बाद invalidation skip करना मतलब UI पुरानी list दिखाता रहता है, भले ही server का data already बदल गया हो।

उदाहरण: Refreshing Related Data After a Mutation

markup
// Run in your local React project (npm install required)
import { useMutation, useQueryClient } from '@tanstack/react-query';

function AddUserForm() {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: newUser => fetch('/api/users', { method: 'POST', body: JSON.stringify(newUser) }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }),
  });
  return <button onClick={() => mutation.mutate({ name: 'Asha' })}>Add User</button>;
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

UI में Mutation Status दिखाना

useMutation से return होने वाला object isPending, isError, और isSuccess flags include करता है, जो UI को request in flight होने पर एक button disable करने, fail होने पर एक error message दिखाने, या succeed होने पर एक confirmation दिखाने देते हैं — वही shape of feedback जो loading/error states को और जगह चाहिए।

Note: Duplicate submissions रोकने के लिए isPending true होने के दौरान trigger button disable करें।
Warning: isError ignore करना मतलब एक failed mutation silently fail होता है, user को कोई idea नहीं होता कि उसका action actually नहीं हुआ।

उदाहरण: Showing Mutation Status in the UI

markup
// Run in your local React project (npm install required)
import { useMutation } from '@tanstack/react-query';

function AddUserForm() {
  const mutation = useMutation({
    mutationFn: newUser => fetch('/api/users', { method: 'POST', body: JSON.stringify(newUser) }),
  });
  return (
    <div>
      <button onClick={() => mutation.mutate({ name: 'Asha' })} disabled={mutation.isPending}>
        {mutation.isPending ? 'Adding...' : 'Add User'}
      </button>
      {mutation.isError && <p>Failed to add user</p>}
    </div>
  );
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक successful mutation के बाद invalidateQueries call करना भूल जाना, stale cached data को displayed छोड़ते हुए।
  2. Mutation के isPending/isError states handle न करना, एक slow या failed write के दौरान कोई feedback न देते हुए।
  3. mutate function को गलत argument shape के साथ call करना, जो mutationFn की expectation से match न करे।
चैप्टर सारांश
  • useMutation create/update/delete operations manage करता है, useQuery के read operations के opposed में।
  • mutate(variables) call करना उन variables के साथ mutationFn trigger करता है।
  • invalidateQueries React Query को बताता है कि एक related query का cached data अब stale है और refetch होना चाहिए।
  • Mutation object appropriate UI feedback दिखाने के लिए isPending, isError, और isSuccess expose करता है।
ब्राउज़र सपोर्ट

npm install @tanstack/react-query चाहिए — इस sandbox में CDN से उपलब्ध नहीं है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.