乐闻世界logo
搜索文章和话题

How to add fresh data to an existing data in React- query ?

1个答案

1

Adding new data to existing data in React-query is commonly used for scenarios such as updating a list after a user submits a form. We can achieve this functionality through several steps:

1. Using useQuery and useMutation

First, we use useQuery to fetch data and useMutation to add new data. useMutation can not only send data to the server but also update the local cache data through its callbacks.

Example Code

Suppose we have a task list, and we want to add a new task to it:

js
import { useQuery, useMutation, useQueryClient } from 'react-query'; function Tasks() { const queryClient = useQueryClient(); const { data: tasks, isLoading } = useQuery('tasks', fetchTasks); const addTaskMutation = useMutation(addTask, { onSuccess: () => { queryClient.invalidateQueries('tasks'); }, }); const handleAddTask = async () => { const newTask = { id: Date.now(), text: 'New Task' }; await addTaskMutation.mutateAsync(newTask); }; if (isLoading) return <div>Loading...</div>; return ( <div> <button onClick={handleAddTask}>Add Task</button> <ul> {tasks.map(task => ( <li key={task.id}>{task.text}</li> ))} </ul> </div> ); }

2. Using onMutate or onSuccess Callbacks to Modify the Cache

In useMutation, the onMutate or onSuccess callbacks can be used to directly modify the cache. This allows the user interface to provide immediate feedback on changes even before the data is synchronized from the server.

  • onMutate: Update the client cache before sending data to the server.
  • onSuccess: Update the client cache after the data is successfully returned from the server.

Example Code - Using onMutate

js
const addTaskMutation = useMutation(addTask, { onMutate: async newTask => { await queryClient.cancelQueries('tasks'); const previousTasks = queryClient.getQueryData('tasks'); queryClient.setQueryData('tasks', old => [...old, newTask]); return { previousTasks }; }, onError: (error, newTask, context) => { queryClient.setQueryData('tasks', context.previousTasks); }, onSettled: () => { queryClient.invalidateQueries('tasks'); }, });

This method provides an optimistic update mechanism, allowing users to see updated data before the network response returns, thereby enhancing application responsiveness and user experience.

3. Summary

By using the above methods, we can effectively add new data to existing data in React-query while maintaining data synchronization and consistency. Using the onMutate or onSuccess callbacks of useMutation to update or roll back data is an effective strategy for handling data updates on the client side, which helps improve application performance and user experience.

2024年6月29日 12:07 回复

你的答案