module-federation / enhanced

Enhanced API for Module Federation
46 stars 2 forks source link

Error "hooks can only be called inside of the body of a function component" #14

Open FrancicoVerdu opened 7 months ago

FrancicoVerdu commented 7 months ago

I am trying to use swr in my host component, but when I use ModuleFederationPlugin, I get an error “hooks can only be called inside of the body of a function component”. This only happens when I use remotes and not when I use exposes. I leave an example of App with SWR to replicate the error, it is not necessary to add the remote component to the App just add it to the remotes inside rsbuild.config.ts. I am using React, Typescript and Rsbuild.

// App.tsx
import "./App.css";
import useSWR from "swr";

const fetcher = (url) => fetch(url).then((res) => res.json());

const App = () => {
  const { data, error, isLoading } = useSWR(
    "https://api.github.com/repos/vercel/swr",
    fetcher
  );

  if (error) return "An error has occurred.";
  if (isLoading) return "Loading...";
  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
      <strong>👁 {data.subscribers_count}</strong>{" "}
      <strong>✨ {data.stargazers_count}</strong>{" "}
      <strong>🍴 {data.forks_count}</strong>
    </div>
  );
};

export default App;
// rsbuild.config.ts
import { defineConfig } from "@rsbuild/core";
import { pluginReact } from "@rsbuild/plugin-react";
import { ModuleFederationPlugin } from "@module-federation/enhanced/rspack";

export default defineConfig({
  server: {
    port: 2000,
  },
  tools: {
    rspack: (config, { appendPlugins }) => {
      appendPlugins([
        new ModuleFederationPlugin({
          name: "federation_consumer",
          remotes: {
            federation_provider:
              "federation_provider@http://localhost:3000/mf-manifest.json",
          },
          shared: ["react", "react-dom", "swr"],
        }),
      ]);
    },
  },
  plugins: [pluginReact()],
});

Captura desde 2024-05-02 12-53-35

VanTigranyan commented 1 month ago

you most likely forgot to add singletion: true to shared deps configuration of react. Also always add required version for react too, so that runtime has easier time understanding which version should be loaded.

VanTigranyan commented 1 month ago

It should be:

shared: {
    'react': { singleton: true, requiredVersion: '^18.3.1' },
    'react-dom': { singleton: true, requiredVersion: '^18.3.1' },
  }