Home > Article > Web Front-end > Real-time data updates using the React Query database plugin
Use the React Query database plug-in for real-time data updates
React Query is a powerful data management tool that can help us simplify the process of processing data in React applications. It provides elegant solutions for operations such as data retrieval, caching and updating. This article will introduce how to use the React Query plug-in to implement real-time data update function, and provide specific code examples.
To better understand this process, we will take a simple task management application as an example. Let's assume that there is a task list in the application. When the user completes a task, we need to update the status of the task in real time.
First, we need to install the React Query plug-in. Run the following command in the terminal:
npm install react-query
After the installation is complete, we can introduce React Query into the root component of the application and create a global QueryClient instance. The code is as follows:
import { QueryClient, QueryClientProvider } from 'react-query'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> {/* 应用组件 */} </QueryClientProvider> ); } export default App;
Next, in the component where we need to update data in real time, create a data update operation by using the useMutation hook provided by React Query. We can define update logic in the click event handler of the task completion button. The specific code is as follows:
import { useMutation, useQueryClient } from 'react-query'; function TaskItem({ task }) { const queryClient = useQueryClient(); const completeTaskMutation = useMutation(async () => { // 发送异步请求完成任务 await fetch(`/api/tasks/${task.id}`, { method: 'PUT', body: JSON.stringify({ completed: true }) }); // 手动更新缓存 queryClient.setQueryData(['tasks', task.id], { ...task, completed: true }); }); const handleCompleteClick = () => { completeTaskMutation.mutate(); } return ( <div> <p>{task.name}</p> <button onClick={handleCompleteClick}>完成</button> </div> ); }
In this code, we first create a variable named completeTaskMutation by calling useMutation. It is an object containing a mutate function, which is used to trigger data update operations.
In the button's click event handler, we call completeTaskMutation.mutate() to trigger data update. This will call the async function we passed in useMutation and after completing the asynchronous request, manually update the data in the cache. Here we use the setQueryData method to update the task data in the cache, and pass in ['tasks', task.id] as the first parameter to indicate that this is a query operation for the task list.
Finally, in the task list component, we use the useQuery hook to obtain task data. The code is as follows:
import { useQuery } from 'react-query'; function TaskList() { const { data } = useQuery('tasks', async () => { const response = await fetch('/api/tasks'); const data = await response.json(); return data; }); return ( <div> {data && data.map(task => ( <TaskItem key={task.id} task={task} /> ))} </div> ); }
In this code, we call useQuery('tasks', ...) to initiate a query operation. The first parameter is the key used to identify the query, here we use 'tasks'. The second parameter is an asynchronous function used to obtain task list data. We can send asynchronous requests in this function and return response data. React Query will automatically cache this data and update it when needed.
Through the above code examples, we successfully used the React Query plug-in to implement the real-time data update function. Whether it is creating new data, updating data or deleting data, React Query can help us manage the data acquisition and update process, greatly simplifying the complexity of processing data in the application. I hope this article will be helpful for you to learn how to use React Query!
The above is the detailed content of Real-time data updates using the React Query database plugin. For more information, please follow other related articles on the PHP Chinese website!