Skip to content

Commit

Permalink
Use object URL API to allow downloading large JSON files (#88)
Browse files Browse the repository at this point in the history
#87 created truncated/unreadable files when the JSON was too big to fit in a data URL. This is a better way to create download links, which works for large files.
  • Loading branch information
sid-kap committed Feb 12, 2024
1 parent 1042766 commit 5c2f824
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
27 changes: 25 additions & 2 deletions lib/PlotsTemplate.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { useEffect, useRef } from "react"

import BarPlot from "lib/BarPlot"
import { CurrentYearExtrapolationInfo } from "lib/projections"
import { useFetch } from "lib/queries"
Expand Down Expand Up @@ -81,7 +83,11 @@ export default function PlotsTemplate({
{selected?.has_ca_hcd_data && <HcdDataInfo />}
</div>
</div>
<DownloadData data={data} name={selected?.name + ".json"} />
<DownloadData
data={data}
name={selected?.name + ".json"}
selected={selected?.name}
/>
</div>
</div>
)
Expand All @@ -90,13 +96,30 @@ export default function PlotsTemplate({
export function DownloadData({
data,
name,
selected,
}: {
data: object
name: string
selected: any

Check warning on line 103 in lib/PlotsTemplate.tsx

View workflow job for this annotation

GitHub Actions / Lint Code Base

Unexpected any. Specify a different type
}): JSX.Element {
const url = useRef("#")

// This runs every time selected changes
useEffect(() => {
url.current = URL.createObjectURL(
new Blob([JSON.stringify(data)], { type: "octet/stream" })
)
// Cleanup function
return () => {
if (url.current != "#" && typeof window !== "undefined") {
URL.revokeObjectURL(url.current)
}
}
}, [selected])

Check warning on line 118 in lib/PlotsTemplate.tsx

View workflow job for this annotation

GitHub Actions / Lint Code Base

React Hook useEffect has a missing dependency: 'data'. Either include it or remove the dependency array

return (
<a
href={"data:application/json," + JSON.stringify(data)}
href={url.current}
className="text-sm text-blue-500 hover:text-blue-300"
download={name}
>
Expand Down
6 changes: 5 additions & 1 deletion pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,11 @@ export default function Home(): JSX.Element {
{perCapitaInput}
{groupingInput}
{selectedLocations.some((l) => l.has_ca_hcd_data) && preferHcdDataInput}
<DownloadData data={data} name="housing data comparisons.json" />
<DownloadData
data={data}
name="housing data comparisons.json"
selected={selectedLocations}
/>
{selectedLocations.some((l) => l.has_ca_hcd_data) && <HcdDataInfo />}
</div>
</Page>
Expand Down

0 comments on commit 5c2f824

Please sign in to comment.