Use figma.ui.postMessage inside figma.ui.onmessage

I can’t figure out why I can’t call figma.ui.postMessage inside the figma.ui.onmessage method. If I call the postMessage method outside the onmessage method my EventListener gets the message. But if I use postMessage like this I don’t receive the message. What am I doing wrong?

figma.showUI(__html__, { themeColors: true, height: 300 });

figma.ui.onmessage = (msg) => {
  figma.ui.postMessage("Test");
  figma.closePlugin();
};

The App.tsx file looks like this:

import React, { useRef } from "react";
import "./App.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faFileExport } from "@fortawesome/free-solid-svg-icons";

function App() {
  const onCreate = () => {
    const count = 5;
    parent.postMessage(
      { pluginMessage: { type: "create-rectangles", count } },
      "*"
    );
  };

  window.addEventListener("message", (event) => {
    const data = "Test data";
    const blob = new Blob([data], { type: "text/plain" });
    let file = URL.createObjectURL(blob);
    let a=document.createElement('a');
    a.download='mydata.txt';
    a.href=file;
    a.click();
  });

  return (
    <main>
      <header>
        <h2>Test</h2>
      </header>
      <footer>
        <button className="download_button" onClick={onCreate}>
          <FontAwesomeIcon icon={faFileExport} />
        </button>
      </footer>
    </main>
  );
}

export default App;

Your plugin is probably closing before the UI can receive the message. Try removing figma.closePlugin() and test again.

Thanks removing closePlugin() worked like a charm.