Should I use a Cell for downloading a file?

Hi, I want to download a (small) text file when user clicks a link.
Should I use a Cell for this use case?
Reading the docs, I saw “use a Cell when you want to fetch data”
But, how to create a Cell that triggers when user clicks a link?

I asked ChatGPT how she´d resolve this and this was the answer (pretty impressive to be honest):

const DownloadLink = () => {
  const [url, setUrl] = useState('')

  const handleClick = async () => {
    const response = await fetch('/.redwood/functions/downloadFile', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({}),
    })
    const { url } = await response.json()
    setUrl(url)
  }

  return (
    <div>
      <button onClick={handleClick}>Download File</button>
      {url && (
        <a href={url} download="myfile.txt">
          Download
        </a>
      )}
    </div>
  )
}

export default DownloadLink

This solution does not use a Cell but seems to work. Any comments or suggestions?
Thanks in advance

Cells help manage your UI during data fetching by providing lifecycle hooks (beforeQuery, afterQuery) and components to render based on the state of the response. It expects the data to be loaded in the client browser’s memory via a GraphQL query.

In your case, using HTML 5’s native download attribute makes more sense. If you use a different file type than *.txt and your endpoint is a Lambda function, you may need to base 64 encode it, since Functions can only return strings or JSON (*.txt files are strings).

1 Like

Thanks for clarifying this.

1 Like