1

I'm using react query.

There is an array of documents (just describing data, no real blobs) with an option to download. They have an onClick handler which calls a function which handles the download.

And in case the user clicks on the download button there is a http request getDocumentById to get the document you want to download.

The Problem is, I can not call my custom query hook in that handleDownload function. But the only place I have my specific document Id is in that function.

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} />
)

How is the best way to handle this?

1 Answer 1

8

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

Then you've come to the right place.

I'm using react query.

That is very good 👍

How is the best way to handle this?

I see two options:

  1. you disable the query and imperatively trigger it with refetch:
const { data, refetch } = useQuery(key, fn, { enabled: false })

<button onClick={() => refetch()} ...>
  1. you don't use a query, but a mutation for it. I think that's the better approach, given that the backend likely creates that document when you click on the button. You also don't want to run it automatically, and you don't want to refetch it with the various refetch options that react-query has, there is also no invalidation necessary, so I'd do:
const { mutate } = useMutation(() => downloadTheDocuments())

<button onClick={() => mutate()} ...>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.