在RTK Query中,当使用Optimistic update(乐观更新)时,我们希望将我们的状态更改体现在UI中,即使后台请求尚未完成。但是,当使用invalidateTags时,我们可以使状态失效并重新获取新数据。这两种技术的使用方式互斥,因为乐观更新将导致状态的不一致性。
因此,我们需要考虑在使用RTK Query时,如何同时使用乐观更新和invalidateTags。
RTK Query为我们提供了一个选项:keepUnusedData。此选项可以使RTK Query通过将我们旧的查询数据标记为“无用”,而不是将其替换为新数据来更新我们的状态。这意味着如果我们的请求失败或已过时,我们将仍然显示我们的旧数据。
在使用乐观更新时,我们可以在我们调用API函数(如useGetPostsQuery)时,将keepUnusedData选项设置为true。这将在我们发出乐观更新时保留我们的旧数据。同时,我们还可以调用invalidateTags函数来使数据失效并重新获取新数据。
以下是示例代码:
import { useGetPostsQuery } from 'src/features/posts/postsAPI';
// 在调用API函数时设置keepUnusedData为true
const { data: posts, isLoading, isError, refetch } = useGetPostsQuery(undefined, {
keepUnusedData: true,
});
// 乐观更新
const handleUpdate = async (postId: string) => {
await updatePost(postId);
// 调用invalidateTags函数
refetch({ forceRefetch: true });
};