HTML React Parser with Asynchronous Replace

87 Views Asked by At

I'm running into a problem with the replace method in HTML React Parser. I'm parsing html where the filename is the alt tag. The file is stored in Firebase, which means I need to execute the asnyc method getDownloadURL provided by firebase to obtain the actual url for the image.

In the code below, the url is correctly console logged out, but the src is never actually replaced. If I take away the async / await from the replace method the src will get swapped out if I put in a dummy string, so the method works, just not asynchronously.

Is there a way to make the replace method wait for the asynchronous return from getDownloadURL before executing the replace?

import parse, { attributesToProps, HTMLReactParserOptions } from "html-react-parser";
import { getDownloadURL, getStorage } from "firebase/storage";

export default function App(){
  
  const storage = getStorage();
  const html = <img src="" alt="file_name" />

  const options: HTMLReactParserOptions = {
    replace: async (domNode: any) => {
      if (!domNode.attribs) {
        return;
      }
      if (domNode.attribs.src) {
        const imageURL = await getDownloadURL(ref(storage, domNode.attribs.alt));
        console.log(imageURL);
        const props = attributesToProps(domNode.attribs);
        return <img {...props} src={imageURL} alt={domNode.attribs.alt} />;
      }
    },
  };



return (
    <div>parse(html, options)</div>
)

0

There are 0 best solutions below