Skip to content

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

@FrancicoVerdu

Description

@FrancicoVerdu

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions