Keep getting error invalid hook call trying to use package c


Topic: Keep getting error "invalid hook call" trying to use package components across microfrontend apps

Bridget Melvin pro premium asked 2 years ago

Expected behavior to render MdbButton in container app as it is imported from (I'm using the pro version and failed to install via npm with access token - it fails from command line every time because command line cannot sign into )

Actual behavior Given I manually downloaded the package and re-configured webpack to act as a remote via ModuleFederationPlugin (as well as created my own /public and /src folders within the root package), I create a file for each MDB React UI Kit component I want to use and create a new remote for that component. The button renders fine within the mdb5 microfrontend app. But when I remote into the button within the container app, the button will not render. Is the container app missing packages or what is missing here? I keep getting this error no matter my configuration.

Resources (screenshots, code snippets etc.)The Error:enter image description here

Directory structure:enter image description here

Container Microfrontend (host):

Header.js:

import React from 'react';
import { useLocation } from 'react-router-dom';

import Logo from './Navbar/Logo';
import ButtonNew from './Navbar/ButtonNew';
import NavTabs from './Navbar/NavTabs';
import NavSelect from './Navbar/NavSelect';
import NavbarContainer from './Navbar/NavbarContainer';
import useStyles from './styling/NavStyle';
import { ButtonMDB } from 'mdbReactMfe/Button';

export default function Header({ isSignedIn, onSignOut }) {
  const classes = useStyles();
  let location = useLocation();

  const onClick = () => {
    // && onSignOut function is ALWAYS TRUE
    if (isSignedIn && onSignOut) {
      onSignOut();
      console.log(isSignedIn)
      //localStorage.clear();
      localStorage.removeItem('sidebar-collapsed');
    }
  };

  const linkMap = [
    ["All Companies", "/companies"],
    ["Company Profile", "/companies/last"], // BEM TO DO: change to dropdown 
    ["Settings", "/user/settings"]
  ];

  return (  
    <React.Fragment>
      <NavbarContainer isSignedIn={isSignedIn} >

          <ul className={classes.navItem} >
            <Logo />
          </ul>
          <ul className={classes.navItem} >
            <div className={classes.navItemMd}>{isSignedIn ? <NavTabs linkMap={linkMap} /> : ''}</div>
            <div className={classes.navItemSm}>{isSignedIn ? <NavSelect linkMap={linkMap} /> : ''}</div>
          </ul>

          <ul className={`${classes.navItem} ${classes.navItemOptional}`}>
            <ButtonNew to={isSignedIn ? '/' : '/auth/signin'} onClick={onClick}>{isSignedIn ? 'Logout' : 'Login'}</ButtonNew>
            {(isSignedIn || location.pathname.includes('auth/')) ? '' : <ButtonNew to='/earlyaccess'>Early Access ➝</ButtonNew>}
            <ButtonMDB />
          </ul>

      </NavbarContainer>
    </React.Fragment>
  );
}

mdb5 Microfrontend (remote):

ButtonMDB.js:

import { MDBBtn } from 'mdb-react-ui-kit';
import React from 'react';

const ButtonMDB = props => {
  return (
    <MDBBtn
    tag='a'
    href='https://mdbootstrap.com/docs/standard/getting-started/'
    target='_blank'
    role='button'
  >
    Start MDB tutorial
  </MDBBtn>
  )
}

export default ButtonMDB

Webpack Config:

webpack.dev.js (remote):

const { merge } = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
const commonConfig = require('./webpack.common');
const packageJson = require('../package.json');
const path = require('path');

const devConfig = {
  mode: 'development',
  output: {
    publicPath: 'http://localhost:8089/',   // don't forget the slash at the end
  },
  devServer: {
    port: 8089,
    historyApiFallback: true,
    open: true,
    compress: true,
    hot: true,
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'mdbReactMod',
      filename: 'remoteEntry.js',
      exposes: {
        // './MDBReactApp': './src/bootstrap',
        './Button': './src/components/buttons/ButtonMDB'
      },
      shared: packageJson.dependencies,
    }),
  ],
};

module.exports = merge(commonConfig, devConfig);

webpack.common.js (remote):

const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
  entry: './app/src/index.tsx',

  output: {
    publicPath: '/',
  },

  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-react', '@babel/preset-env'],
            plugins: ['@babel/plugin-transform-runtime'],
          },
        },
      },
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.((c|sa|sc)ss)$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        use: 'file-loader',
      },
      {
        test: /\.(woff|woff2)$/,
        use: 'url-loader?prefix=font/&limit=5000',
      },
      {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        use: 'url-loader?limit=10000&mimetype=application/octet-stream',
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        use: 'url-loader',
      },
      {
        test: /\.png(\?v=\d+\.\d+\.\d+)?$/,
        use: 'url-loader?limit=10000&mimetype=image/png',
      },
      {
        test: /\.gif(\?v=\d+\.\d+\.\d+)?$/,
        use: 'url-loader?limit=10000&mimetype=image/gif',
      },
    ],
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: 'public/index.html',
    }),
  ],

  resolve: {
    extensions: ['.tsx', '.ts', '.js', 'd.ts', '.json', '.css'],
    alias: {
      'mdb-react-ui-kit': path.resolve('./app/src/index.tsx'),
    },
  },
};

  1. What errors do you get while installing with npm?
  2. You could try downloading the zip: mdb-react-ui-kit-4.0.0.tgz from the mdbootstrap site then paste it to your root project and link it in package.json as normal dependency (like here: "mdb-react-ui-kit": "./mdb-react-ui-kit-4.0.0.tgz"). Of course run npm install after.

Bridget Melvin pro premium commented 2 years ago

(1) When installing with npm with an access token, I get two similar errors on npm run start that reflect my two import statements where I import from 'mdb-react-ui-kit'

ERROR in resolving fallback for shared module mdb-react-ui-kit

Module not found: Error: Can't resolve 'git+https://oauth2:{my-token}@git.mdbootstrap.com/mdb/react/mdb5/prd/mdb5-react-ui-kit-pro-essential#3.0.0

(2) That is what I did and I got the error in my original post


Wojciech Staniszewski staff commented 2 years ago

Could you create a GitHub repository where you can recreate this problem? Hard to debug without it.


Bridget Melvin pro premium commented 2 years ago

I was able to fix the error in my prior comment by creating an alias for 'mdb-react-ui-kit' in the resolve property of webpack config, but react still remits an error. See repo

https://github.com/theCosmicGame/mdb-test host: containerNew remote: table

I get an invalid hook call when trying to use the remote's exposed 'MDBButton' custom component (see Header.js in the containerNew mfe and MDBButton.js in the table mfe .. both mfes are using the same version of react


Wojciech Staniszewski staff commented 2 years ago

You do not have any MDB version installed in the mdb catalog. Also, you probably have the wrong key while installing with npm.


Bridget Melvin pro premium commented 2 years ago

the problem is replicated in the table directory -- because I could not get the mdb directory to work ... the key published on github was subsequently deleted from gitlab for security reasons


Wojciech Staniszewski staff commented 2 years ago

I'm sorry, but we could not install/run your project however we try (for reasons unrelated to MDB).


Bridget Melvin pro premium commented 2 years ago

I was able to clone the repo and successfully run npm install on both containerNew and table


Bridget Melvin pro premium commented 2 years ago

I eventually got this to work with a lot of reworking especially on the HOC.. thanks for the help


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue
  • User: Pro
  • Premium support: Yes
  • Technology: MDB React
  • MDB Version: MDB5 4.0.0
  • Device: Laptop
  • Browser: Chrome
  • OS: Windows 11
  • Provided sample code: No
  • Provided link: No