Answer:
When using React Query for form submission, it is commonly employed for asynchronous data queries and cache management rather than directly handling form submission. However, you can combine React Query with other form handling libraries (such as Formik) to effectively manage data and update server states. Here is an example of using React Query to handle a form with asynchronous submission:
1. Installing and Setting Up React Query
First, ensure you have installed React Query. If not, install it using npm or yarn:
bashnpm install react-query # or yarn add react-query
Next, set up the React Query client in your React application:
javascriptimport { QueryClient, QueryClientProvider } from 'react-query'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> {/* Other parts of your application */} </QueryClientProvider> ); }
2. Creating the Form Component
You can use any form library to create the form; here's an example with a simple HTML form:
javascriptimport { useMutation } from 'react-query'; function Form() { const { mutate, isLoading, isError, error } = useMutation(submitFormData); function handleSubmit(event) { event.preventDefault(); const formData = new FormData(event.target); mutate(formData); } return ( <form onSubmit={handleSubmit}> <input type="text" name="username" required /> <input type="password" name="password" required /> <button type="submit" disabled={isLoading}>Submit</button> {isError && <p>Submission failed: {error.message}</p>} </form> ); }
3. Defining the Submission Function
submitFormData is an asynchronous function used to handle form data submission. For example, it can call an API endpoint:
javascriptasync function submitFormData(formData) { const response = await fetch('/api/submit-form', { method: 'POST', body: formData, }); if (!response.ok) { throw new Error('Network error'); } return response.json(); }
4. Using useMutation
In React Query, the useMutation hook is used for handling asynchronous logic (such as data submission). It provides the mutate method to trigger the asynchronous function and state flags like isLoading and isError to display loading states and handle errors in the UI.
Summary
By following these steps, you can leverage React Query in your React application to manage form submission states and caching, maintaining UI responsiveness and data consistency. This approach effectively separates form data handling logic from UI rendering logic, enhancing maintainability and scalability.