Created
          September 5, 2023 16:03 
        
      - 
      
- 
        Save lebbe/83679f5ab9e8029fdac5df53ae9fb8b6 to your computer and use it in GitHub Desktop. 
Revisions
- 
        lebbe created this gist Sep 5, 2023 .There are no files selected for viewingThis file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,46 @@ /** * This hook returns an URL you can use in the href-attribute of an anchor element, * so the provided string will be downloaded as a txt-file. */ function useTxtBlobifier(document: string) { const [loading, setLoading] = useState(true); const [url, setUrl] = useState(''); // Remove the unused url instance if/when the document // changes, or when component unmounts. useEffect(() => { return () => { if (url) { URL.revokeObjectURL(url); } }; }, [url]); const instance = { loading, url }; useEffect( function () { if (document && typeof document === 'string') { // Fix typesetting issues if document is opened in the browser // (typically new tab, instead of downloading) const BOM = new Uint8Array([0xef, 0xbb, 0xbf]); const blob = new Blob([BOM, document], { type: 'text/plain', }); setUrl(URL.createObjectURL(blob)); setLoading(false); } else { setLoading(true); } }, [document] ); return { url, loading }; } // TODO: I could release a component into npm that resembles react-pdf, only for txt-files instead.