reactjs 如何在React查询中添加新数据以使用InfiniteQuery?

ycl3bljg  于 2023-02-18  发布在  React
关注(0)|答案(1)|浏览(101)

我开始使用React Query并使用useInfiniteQuery钩子进行无限滚动,但我想实现的新功能是add new post(新元素),新元素将添加到useInfiniteQuery中数组data的开头。
我的示例代码:

const { status, data, error, isFetching, isFetchingNextPage, fetchNextPage, hasNextPage } = useInfiniteQuery(
        ['posts'],
        async ({ pageParam = '' }) => {
            const res = await postAPI.getPost(as, pageParam, PAGE_LIMIT);
            return res;
        },
        {
            getNextPageParam: (lastPage) =>
                lastPage.length && lastPage.length >= 5 ? lastPage[lastPage.length - 1]?.id : undefined,
        },
    );

   ...
   <button onClick={() => data.unshift(...)}>Add new data</button> // this idea of ​​mine doesn't seem to work

我可以用queryClient.setQueryData(queryKey, newData)来实现这个吗?

ffscu2ro

ffscu2ro1#

const mutation = useMutation({
    mutationFn: (body) => addPost(body),
    onSuccess: (newPost) => {
        queryClient.setQueryData(['posts'], (oldData) => ({
            pages: [[newPost],...oldData.pages],
            pageParams: [...oldData.pageParams, { cursor: newPost.id }],
        }))

}、})
〈button onClick={()=〉变异.变异(正文)}〉

相关问题