Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
FrancicoVerdu opened this issue May 2, 2024 · 2 comments

Comments

@FrancicoVerdu
Copy link

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
Copy link

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
Copy link

It should be:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants