reactjs 在服务器响应正常但不包含实际数据的情况下,react-query是否有办法重新验证缓存数据?

6ie5vjzr  于 2023-01-25  发布在  React
关注(0)|答案(1)|浏览(98)

我正在研究react-query,但找不到一个特定用例的示例。
演示todo API服务器返回以下JSON for getTodos(ifModifiedSince=1234567)请求:
如果自指定时间以来未修改待办事项列表:{"status":"not_modified"}
否则:{"status":"ok","todos":[{"userId":1,"id":2,"title":"TodoItem1","completed":false}],"lastModified":"1234589"}
我想到的最接近的:

const { isLoading, isError, data } = useQuery(
    [todosQueryKey],
    () => {
      const lastModified = data?.lastModified || '';
      const result = getTodos({
        ifModifiedSince: lastModified,
      });
      return result;
    },
    {
      select: (newData): GetTodosResponse | undefined => {
        let resolvedData = newData;
        if (newData.status === StatusNotModified) {

          //! This actually does not work because getQueryData
          //! already returns data from most recent 'not_modified' request.
          resolvedData = queryClient.getQueryData([todosQueryKey]) || newData;
        }

        resolvedData.todos?.sort((a: TodoItem, b: TodoItem) => b.id - a.id);
        return resolvedData;
      },
      refetchInterval: 5000,
      staleTime: Infinity,
      keepPreviousData: true,
    }
  );

使用React查询完成上述任务的正确方法是什么?

aiazj4mn

aiazj4mn1#

我目前的解决方案是像往常一样使用useQuery(),但修改getTodos()函数,使其接收缓存数据作为可选的第二个参数,并在status==='not_modified'

export const getTodos = async (
  req: GetTodosRequest,
  currentData?: GetTodosResponse | undefined
): Promise<GetTodosResponse> => {
  return todosApi
    .get(`/todos/`, {
      params: req,
    })
    .then((resp) => {
      const newData = validateResponse(resp);
      if (newData.status === StatusNotModified) {
        // If server responded with StatusNotModified,
        // return cached data if any.
        return currentData || newData;
      }
      return newData;
    });
};

const { isLoading, isError, data } = useQuery(
    [todosQueryKey],
    () => {
      const lastModified = data?.lastModified || '';
      const result = getTodos(
        {
          ifModifiedSince: lastModified,
        },
        data
      );
      return result;
    },
    {
      select: (newData): GetTodosResponse => {
        newData.todos?.sort((a: TodoItem, b: TodoItem) => b.id - a.id);
        return newData;
      },
      onSuccess: () => {
        setWaitingForResponse(false);
      },
      refetchInterval: 5000,
      staleTime: Infinity,
    }
  );

相关问题