使用数组对象在 onClickHandler 中调用 useQuery

useQuery call in onClickHandler with object of array

我正在使用反应查询。

有一组文档(仅描述数据,没有真正的 blob),可以选择下载。他们有一个 onClick 处理程序,它调用一个处理下载的函数。

如果用户单击下载按钮,则会有一个 http 请求 getDocumentById 来获取您要下载的文档。

问题是,我无法在该 handleDownload 函数中调用我的自定义查询挂钩。但是我唯一拥有特定文档 ID 的地方就是那个函数。

const parseDocuments = () => {
    return documents.map(document => ({
      ...document,
      name: document.fileName,
      date: formatDateForUI(new Date(document.created)),
      downloadDocumentHandler: () => downloadFileClickHandler(document),
      read: document.read
    }));
  }

function handleDownload(document) {
  <here I need to call the getDocumentById>
}

return (
  <DocumentsTable documents={parseDocuments()} headers={headers} accountId={accountId} />
)

最好的处理方法是什么?

I've got a problem I don't know the answer.

那么你来对地方了。

I'm using react query.

非常好

How is the best way to handle this?

我看到两个选项:

  1. 您禁用查询并使用 refetch:
  2. 强制触发它
const { data, refetch } = useQuery(key, fn, { enabled: false })

<button onClick={() => refetch()} ...>
  1. 您不使用查询,而是使用 mutation。我认为这是更好的方法,因为当您单击按钮时后端可能会创建该文档。您也不希望自动 运行 它,并且您不想使用 react-query 具有的各种重新获取选项重新获取它,也没有必要的无效,所以我会这样做:
const { mutate } = useMutation(() => downloadTheDocuments())

<button onClick={() => mutate()} ...>