Hydrate SSR components with fetch call

Hi!

I have a stencil component (build with lit) which make a fetch request in componentWillLoad event.

At browser it works like a charm, but when I try to build a static HTML using renderToString I am getting the error:

Error: fetch() not implemented

Which is triggered by the hydrate script created by the stencil build.

import { Component, Host, h, Prop, State, Watch } from '@stencil/core';

@Component({
  tag: 'counting-result',
})
export class CountingResult {
  async requestJsonData() {
    const json = await fetch(`https://api.hostname.com/mock.json`).then(res => res.json());

    document.dispatchEvent(new CustomEvent('dataResult', {
      detail: json,
    }));
  }

  componentWillLoad() {
    this.requestJsonData();
  }

  render() {
    return (
      <Host>
        <slot></slot>
      </Host>
    );
  }
}
const hydrate = require('./hydrate/index.js');

;(async() => {
  const results = await hydrate.renderToString('<counting-result></counting-result>', {
    prettyHtml: true,
    removeScripts: true
  });

  console.log(results.html)
})();

I have tried to install fetch-node and expose it to global or change the hydrated script to use the fetch-node but I have no success.

Somebody knows if it is a Stenciljs limitation/bug or if I need to install some dependencie?

Ok, I have found one issue in my implemetation. The componentWillLoad should be sync, otherwise the render() will occorus without data.

In frontend (browser) a re-render is triggered, but using renderToString the data never goes to component state.

Fixing it, and making a global.fetch does the code works.

async componentWillLoad() {
    await this.requestJsonData();
}
const hydrate = require('./hydrate/index.js');
global.fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

;(async() => {
  const results = await hydrate.renderToString('<counting-result></counting-result>', {
    prettyHtml: true,
    removeScripts: true
  });

  console.log(results.html)
})();