preactjs / preact

⚛️ Fast 3kB React alternative with the same modern API. Components & Virtual DOM.
https://preactjs.com
MIT License
36.79k stars 1.95k forks source link

Hooks broken in pure browser aka "no build tools route" #4477

Closed psydvl closed 2 months ago

psydvl commented 2 months ago

Describe the bug preact/hooks.useState (or any other hook) broken if used as is

To Reproduce

https://periwinkle-tabby-lasagna.glitch.me https://glitch.com/edit/#!/periwinkle-tabby-lasagna

Steps to reproduce the behavior:

  1. copy and paste to browser url
    data:text/html,<script type="module">
    import { useState } from "https://esm.sh/preact/hooks";
    const [foo, setFoo] = useState(0);
    </script>
  2. Open console Firefox: Ctrl+Shift+K Chrome-based: Ctrl+Shift+J
  3. See error: Firefox
    Uncaught TypeError: r is undefined
        Preact 4
            l
            I
            B
            <anonymous>
    index.js:148:2

    Chrome-based

    Uncaught TypeError: Cannot read properties of undefined (reading '__H')
        at l (index.js:148:19)
        at I (index.js:181:20)
        at B (index.js:168:9)
        at (index):21:29

Expected behavior No error, since this hooks mentioned in https://preactjs.com/guide/v10/no-build-workflows/#preact-with-hooks-signals-and-htm No-Build Workflows -> Recipes and Common Patterns -> Preact with Hooks, Signals, and HTM

JoviDeCroock commented 2 months ago

Context here https://github.com/preactjs/preact/issues/2564#issuecomment-636316811 - are you leveraging an import map as mentioned in your link? Hmm, this might be an issue in glitch 😅 but yes import-maps should work as used by fresh, alternatively you can use the knowledge of the aforementioned link

JoviDeCroock commented 2 months ago

Oh.... You aren't using the hook in a component... That can't work 😅 https://glitch.com/edit/#!/intermediate-wide-watch?path=index.html%3A19%3A26

    <script type="importmap">
      {
        "imports": {
          "preact": "https://esm.sh/preact@10.23.1",
          "preact/": "https://esm.sh/preact@10.23.1/",
          "@preact/signals": "https://esm.sh/@preact/signals@1.3.0?external=preact",
          "htm/preact": "https://esm.sh/htm@3.1.1/preact?external=preact"
        }
      }
    </script>
    <p id="console"></p>
    <script type="module">
      window.addEventListener("error", (err) => {
        document.querySelector("#console").innerHTML = [
          err.filename,
          err.lineno,
          err.colno,
          err.message,
        ].join(": ");
      });
      import { render } from 'preact';
      import { html } from 'htm/preact';
      import { useState } from 'preact/hooks';

      export function App() {
        const [state, setState] = useState('world')
        return html`
          <h1>Hello, ${state}!</h1>
        `;
      }

      render(html`<${App} />`, document.body);
    </script>