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

React TypeError: Cannot read properties of null (reading 'useState') #294

Open
guoxiaxing opened this issue Nov 29, 2022 · 77 comments · Fixed by #345
Open

React TypeError: Cannot read properties of null (reading 'useState') #294

guoxiaxing opened this issue Nov 29, 2022 · 77 comments · Fixed by #345
Labels
bug Something isn't working has workaround

Comments

@guoxiaxing
Copy link

Versions

  • vite-plugin-federation: 1.1.10
  • vite: 3.2.3

Reproduction

Additional Details

clone this repo https://github.com/guoxiaxing/vite-FM,
cd into each directory and run pnpm install. cd remote directory and run pnpm build && npx vite preview --port=3001 --strictPort, then cd host directory and run pnpm run dev.

Steps to reproduce

above

What is Expected?

all working

What is actually happening?

but http://localhost:5173/ not work, and throw Uncaught TypeError: Cannot read properties of null (reading 'useState')
at react_production_min.useState
image

@Yulingsong
Copy link

遇到同样的问题了,请问有解决吗

@Rudel-git
Copy link

the same. It looks no bad until importing react. the examples don't consist of any react imports

@flyfishzy flyfishzy added the bug Something isn't working label Jan 5, 2023
@flyfishzy
Copy link
Member

Please try to upgrade to vite 4.0 & @originjs/vite-plugin-federation ^1.1.13

image

@Rudel-git
Copy link

Rudel-git commented Jan 14, 2023

host: dev
remote: preview
shared: ['react', 'react-dom']

Versions

  • "@originjs/vite-plugin-federation": "^1.1.13",
  • "vite": "^4.0.4",
  • "@vitejs/plugin-react": "^3.0.1",
  • "react": "^18.2.0",
  • "react-dom": "^18.2.0"

updated and now got. reactexports is undefined, default has the value

image
image
image

@toanil315
Copy link

toanil315 commented Jan 15, 2023

host: dev remote: preview shared: ['react', 'react-dom']

Versions

  • "@originjs/vite-plugin-federation": "^1.1.13",
  • "vite": "^4.0.4",
  • "@vitejs/plugin-react": "^3.0.1",
  • "react": "^18.2.0",
  • "react-dom": "^18.2.0"

updated and now got. reactexports is undefined, default has the value

image image image

@RudikS-git , @flyfishzy
same problem, do you have any update about this?

@flyfishzy
Copy link
Member

Can you provide a reproduction repo? @RudikS-git @toanil315

@TimKolberger
Copy link

I created a reproduction for the original error with updated versions here: https://github.com/TimKolberger/issue-reproduction-vite-federated-modules

I prepared the repo be easy to setup:

git clone [email protected]:TimKolberger/issue-reproduction-vite-federated-modules.git repro-issue-294 \
  && cd $_ \
  && pnpm install \
  && pnpm build \
  && pnpm preview

Error

Cannot read properties of null (reading 'useState')

image

_federation_shared_ is registered, but not used:

image

Versions in host and remote project:

  "dependencies": {
    "react": "18.2.0",
    "react-dom": "18.2.0",
    ...
  },
  "devDependencies": {
    "@originjs/vite-plugin-federation": "1.1.14",
    "@vitejs/plugin-react": "3.0.1",
    "vite": "4.0.4",
    ...
  }

Host vite.config.ts:
https://github.com/TimKolberger/issue-reproduction-vite-federated-modules/blob/main/packages/host/vite.config.ts

Remote vite.config.ts:
https://github.com/TimKolberger/issue-reproduction-vite-federated-modules/blob/main/packages/widget/vite.config.ts

@0ro
Copy link

0ro commented Jan 23, 2023

I have the same issue. Any ideas on how to quickly fix it?

@chiffenok
Copy link

chiffenok commented Jan 23, 2023

I have the same issue. Any ideas on how to quickly fix it?

I'm joining to the question . I just switch from create-react-app to vite and really love it. don't want to switch to webpack just to use webapack Module federation plugin

@toanil315
Copy link

toanil315 commented Jan 23, 2023

I have the same issue. Any ideas on how to quickly fix it?

If you just want to run it, so delete line shared: ['react', 'react-dom'], it work for me. Waiting for @flyfishzy fix it
The error happened to me was vite shared create 2 instance of react and this cause error

@0ro
Copy link

0ro commented Jan 23, 2023

If you just want to run it, so delete line shared: ['react', 'react-dom'], it work for me. Waiting for @flyfishzy fix it
The error happened to me was vite shared create 2 instance of react and this cause error

It still doesn't work I have a host application with React and two remotes with the same React version. I already tried a lot of combinations with shared options and no one works. @flyfishzy you are only my hope, I don't want to go back to CRA

@Sergey-Makkoev
Copy link

I have the same problem when using ant design. I also tried everything, nothing helps.

When I add the ant design component, an error appears: Uncaught TypeError: Cannot read properties of null (reading 'useContext')

@mndbndr
Copy link

mndbndr commented Jan 28, 2023

@flyfishzy wrote:

Can you provide a reproduction repo? @RudikS-git @toanil315

@flyfishzy you can break the existing example "react-vite" in this repo just by adding "const [ state ] = React.useState(0);" to the Button.jsx. You don't even have to use the state variable anywhere.

Here is the full modified Button.jsx file:

    import React from "react";
    import "./Button.css";

    export default ({caption = "Shared Button"}) => {
        const [ state ] = React.useState(0);

        return (
            <button className='shared-btn'>{caption}</button>
        )
   }

I am in the same boat as everyone else. I love Vite and need module federation and don't want to go back to webpack. Please advise. Thank you.

@flyfishzy flyfishzy added working on This work is being done and removed has workaround labels Jan 30, 2023
@grzesiek-ds
Copy link

grzesiek-ds commented Jan 31, 2023

Hello @flyfishzy I see that You picked up this issue few days ago, thats great!
I just wanted to highlight that the same issue (but different error) applies to react 17.
React is throwing error https://reactjs.org/docs/error-decoder.html/?invariant=321 but from what I've noticed, it appears that react instance is also equal to null (same problem as react 18).

There are two minimal repos with reproduced issue.
Notice that I also want to consume module inside of worker file. This is something that is not working in webpack, but it does in vite 🎆

https://github.com/grzesiek-ds/vite-host
https://github.com/grzesiek-ds/vite-module

@rastiben
Copy link

rastiben commented Feb 1, 2023

Hello, I actually have the same problem with Vite 4. The problem does not occur with Vite 2.8. I see that work is in progress on it but I wanted to know what you advise. We have a rather urgent need to share a module present in a Vite config and to use it in a Webpack config. Do you recommend leaving Vite for now?

@chiffenok
Copy link

Hello, I actually have the same problem with Vite 4. The problem does not occur with Vite 2.8. I see that work is in progress on it but I wanted to know what you advise. We have a rather urgent need to share a module present in a Vite config and to use it in a Webpack config. Do you recommend leaving Vite for now?

@rastiben for me it's not working with Vite 2.8 neither (( Do you maybe have reproduction code?

flyfishzy added a commit to flyfishzy/vite-plugin-federation that referenced this issue Feb 9, 2023
@flyfishzy flyfishzy added has workaround and removed working on This work is being done labels Feb 11, 2023
@flyfishzy
Copy link
Member

We have released a new version v1.2.0, please try this version and check if the problem is fixed.

@rastiben
Copy link

I confirm that it works perfectly! Thank you very much for the work!

@Sergey-Makkoev
Copy link

I updated to version 1.2. But I have the same error. As soon as a component from antd appears in the remote project, an error appears: Cannot read properties of null (reading 'useState').

https://github.com/Sergey-Makkoev/vite-antDesign

8

@ytftianwen
Copy link

Same error here,cann't use useState in shared component, any idea about this?

@chiffenok
Copy link

chiffenok commented Feb 13, 2023

Same error here,can't use useState in shared component, any idea about this?

For me, it seems to work so far. Maybe try to make sure that the package really updated? I mean I needed to remove /node_modules and yarn.lock because the old version was cached

@ytftianwen
Copy link

ytftianwen commented Feb 14, 2023

Same error here,can't use useState in shared component, any idea about this?

For me, it seems to work so far. Maybe try to make sure that the package really updated? I mean I needed to remove /node_modules and yarn.lock because the old version was cached

Year, it works finally, thks~

@kabala
Copy link

kabala commented Aug 16, 2023

Same issue with NextJS nextjs-mf plugin

I'm facing the same issue in next.js 12 with the mocdule working with cra/craco

@leandrodevarona
Copy link

I am also having this problem

@erkanisuf
Copy link

erkanisuf commented Aug 24, 2023

It started to work now to me. Before it was crashing in dev server but work fine in build mode. Now works for both.
i dont know if this is related to this but i was using node js 16 then i upgraded to 18 also npm to v9+
i deleted node modules, removed packa lock and removed cache of modules too and then just reinstalled. Not sure if this was the case but seems to work now for dev and build mode.

@leandrodevarona
Copy link

My problem was with component imports. If I had a component A of a microservice X that imported a component B of a microservice Y, and component B also imported a component of the microservice X, it gave an error. I solved it by creating a microservice that contained the common components and it no longer gives me an error.

@rubenberna
Copy link

Hi,

Just to add here and following the setup in react-vite example.

"@originjs/vite-plugin-federation": "^1.3.2"

I'm using "@mui/material": "^5.14.11", and I get this error on the host preview:

image

This or something similar has happened with other packages installed in remote. Unless remote is very simple, it tends to break in the build. I would really like to use this plugin and it would make a big difference in the architecture of my app, and I could be wrong, but it seems that it's not yet totally ready for React.

@bluedusk
Copy link

same issue here, is this issue being looked at at all ? this make the plugin useless for React

@adamsimonini
Copy link

I am experiencing the same issue.

Node 2.10.0

My team and I are trying to load in a bunch of web games from the remote react app to a host react app. Some of the games work (namely Phaser2 and Phaser3 games), but the unit game fails, and the only error we get is "TypeError: Cannot read properties of null (reading 'useState')"

image

@rodoabad
Copy link

I believe this issue just like what everyone says, makes originjs/vite-plugin-federation useless beyond quick TODO demos.

cc @ruleeeer or any other contributors?

@rodoabad
Copy link

I just realized this works in production/build mode. But it doesn't work in dev server of Vite -_^ any ideas? 😿

Your remote file only gets built when you build not when you use development mode.

@codeandgyan
Copy link

codeandgyan commented Feb 16, 2024

I am using vite as remote and webpack as host. I too am getting this error Cannot read properties of null (reading 'useState').

Remote (vite):

"@originjs/vite-plugin-federation": "^1.2.3",
"react": "^18.2.0",
"react-dom": "^18.2.0"

Host (webpack):

"html-webpack-plugin", "^5.5.0"
"react": "17.0.0",
"react-dom": "17.0.0"

Even if I upgrade my host react version to 18.2.0, it doesn't work and I get the same error. So it doesn't seem to me as react version issue.

This issue is really blocking me I don't have a confidence in integrating this plugin. Would appreciate any steps towards resolution. Thanks!

@adirzoari
Copy link

@codeandgyan @rodoabad same issue, any solution?

@jean-moreira-ihm
Copy link

have a solution to that? I had the same problem here! I try to esposes the reactflow to other project.

Screenshot from 2024-04-04 15-55-16

@danielm2402
Copy link

I have a similar problem, I am using xstate on my remote, when I call it from the host I get:

Cannot read properties of null (reading 'useRef')
    at react_production_min.useRef (__federation_shared_react-CWDiSrc2.js:58:402)
    at withSelector_production_min.useSyncExternalStoreWithSelector (react-BtpD9vXH.js:40:88)
    at useMachine (react-BtpD9vXH.js:292:45)

One solution that seems to work is to put xstate in shared on the host and remote. But I don't see the point in having the xstate dependency on my host since I don't need it there. Does anyone have any idea how to fix it? I don't want to switch to webpack

I am using the following versions

"@originjs/vite-plugin-federation": "^1.3.5",
"vite": "^5.1.0"
"react": "^18.2.0",
"react-dom": "^18.2.0",

@testrobpoc
Copy link

I have a similar problem, I am using xstate on my remote, when I call it from the host I get:

Cannot read properties of null (reading 'useRef')
    at react_production_min.useRef (__federation_shared_react-CWDiSrc2.js:58:402)
    at withSelector_production_min.useSyncExternalStoreWithSelector (react-BtpD9vXH.js:40:88)
    at useMachine (react-BtpD9vXH.js:292:45)

One solution that seems to work is to put xstate in shared on the host and remote. But I don't see the point in having the xstate dependency on my host since I don't need it there. Does anyone have any idea how to fix it? I don't want to switch to webpack

I am using the following versions

"@originjs/vite-plugin-federation": "^1.3.5",
"vite": "^5.1.0"
"react": "^18.2.0",
"react-dom": "^18.2.0",

I have exactly the same issue when using some 3rd party library in remote MFE. And Only if I put that dependency to the Host, then it works fine, but that shouldn't be like that, because Host don't need to know anything about that dependency... I Have a bad feeling that this plugin is useless for now... since this issue was raised more than a year ago and still it wasn't fixed.

@Cafezinho
Copy link

Any update?????????

@ajithsimons
Copy link

Any update??????

@sahaam
Copy link

sahaam commented May 18, 2024

Any update? Still facing the same issue

@JessYan0913
Copy link

any update?

@nguyenbatranvan
Copy link

any update?

The project seems to have been out of development for a long time

@danielm2402
Copy link

In case anyone is interested... I ended up using webpack on my remote with ModuleFederationPlugin and on my host vite-plugin-federation. I have a suspicion that it's more of a vite problem than a plugin problem.

@ajithsimons
Copy link

webpack

Could you please share your webpack configuration in remote.

@danielm2402
Copy link

danielm2402 commented May 22, 2024

webpack

Could you please share your webpack configuration in remote.

Sure, I leave you the remote and host respectively.

module.exports = {
    entry: './src/main',
    mode: 'development',
    target: 'es2020',
    devtool: false,
    experiments: {
        outputModule: true
    },
    devServer: {
        static: path.join(__dirname, 'dist'),
        port: 3000,
        headers: {
            'Access-Control-Allow-Origin': '*', 
            'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
            'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization'
        }
    },
    output: {
        publicPath: 'auto',
    },
    module: {
        rules: [
            {
                test: /\.js|\.jsx$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                options: {
                    presets: ['@babel/preset-react'],
                },
            },
            {
                test: /\.css$/i,
                use: ["style-loader", "css-loader"],
            },
            {
                test: /\.ts|\.tsx$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            }
        ],

    },
    plugins: [
        new ModuleFederationPlugin({
            name: 'remoteApp',
            library: { type: 'module' },
            filename: 'remoteEntry.js',
            exposes: {
                './App': './src/App.jsx',
            },

            shared: { react: { singleton: true, requiredVersion: '18.2.0' }, 'react-dom': { singleton: true, requiredVersion: '18.2.0' } },
        }),
        new HtmlWebpackPlugin({
            template: './index.html',
        }),
    ],
    resolve: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
    },
};
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  return {
    plugins: [react(),
    federation({
      name: 'app',
      remotes: {
        remoteApp: {
          external: 'http://localhost:3000/remoteEntry.js',
          format: 'esm',
          from: 'webpack'
        }
      },
      shared: ['react', 'react-dom']
    })],
    envDir: './environments',
    define: {
      'import.meta.env.APP_VERSION': JSON.stringify(env.npm_package_version)
    },
    build: {
      target: 'esnext' //browsers can handle the latest ES features
    }
  }
})

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑‍🤝‍🧑👫🧑🏿‍🤝‍🧑🏻👩🏾‍🤝‍👨🏿👬🏿


webpack

Could you please share your webpack configuration in remote.

Claro, te dejo el remoto y el host respectivamente

module.exports = {
    entry: './src/main',
    mode: 'development',
    target: 'es2020',
    devtool: false,
    experiments: {
        outputModule: true
    },
    devServer: {
        static: path.join(__dirname, 'dist'),
        port: 3000,
        headers: {
            'Access-Control-Allow-Origin': '*', 
            'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
            'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization'
        }
    },
    output: {
        publicPath: 'auto',
    },
    module: {
        rules: [
            {
                test: /\.js|\.jsx$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                options: {
                    presets: ['@babel/preset-react'],
                },
            },
            {
                test: /\.css$/i,
                use: ["style-loader", "css-loader"],
            },
            {
                test: /\.ts|\.tsx$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            }
        ],

    },
    plugins: [
        new ModuleFederationPlugin({
            name: 'remoteApp',
            library: { type: 'module' },
            filename: 'remoteEntry.js',
            exposes: {
                './App': './src/App.jsx',
            },

            shared: { react: { singleton: true, requiredVersion: '18.2.0' }, 'react-dom': { singleton: true, requiredVersion: '18.2.0' } },
        }),
        new HtmlWebpackPlugin({
            template: './index.html',
        }),
    ],
    resolve: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
    },
};
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  return {
    plugins: [react(),
    federation({
      name: 'app',
      remotes: {
        remoteApp: {
          external: 'http://localhost:3000/remoteEntry.js',
          format: 'esm',
          from: 'webpack'
        }
      },
      shared: ['react', 'react-dom']
    })],
    envDir: './environments',
    define: {
      'import.meta.env.APP_VERSION': JSON.stringify(env.npm_package_version)
    },
    build: {
      target: 'esnext' //browsers can handle the latest ES features
    }
  }
})

@tiennguyen1293
Copy link

I've been exploring building a library with Vite + React, and I'm facing this issue.

I am using the following versions

"vite": "^5.4.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",

@baba43
Copy link

baba43 commented Sep 22, 2024

I wanted to give vite a try and just came across this issue. No idea why this happens or how to fix it. So sad.

@sebas-deedee
Copy link

Any update on this issue?

@AbhayVAshokan
Copy link

If you are building an NPM package and using it in a different application, you need to make sure that your package does not introduce two versions of React.

Step 1: Add react and react-dom as peer dependencies to your package.json file.

"peerDependencies": {
  "react": "^18",
  "react-dom": "^18"
}

Step 2: Add react and react-dom as external dependencies in your vite config:

export default defineConfig({
  build {
    rollupOptions: {
      external: ["react", "react-dom"],
    },
  }
});

Done. If you need a more robust approach, use the below code instead:

import packageJson from "./package.json";

export default defineConfig({
  build {
    rollupOptions: {
      external: Object.keys(packageJson.peerDependencies),
    },
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working has workaround
Projects
None yet