Creating react/typescript library resulting in Invalid hook call error

huangapple go评论73阅读模式
英文:

Creating react/typescript library resulting in Invalid hook call error

问题

I am building a react/typescript library using typescript and rollup to export it
this is my package.json for library

{
"name": "infosysta-typescript-core",
"version": "1.0.0",
"description": "This will the infosysta's core library for typescript",
"scripts": {
"build_tsc": "tsc",
"build_publish": "tsc -p .",
"publish": "npm publish",
"start": "tsc && nodemon build/index.js",
"rollup": "rollup -c"
},
"keywords": [],
"author": "Infosysta",
"license": "ISC",
"devDependencies": {
"@atlaskit/adf-schema": "^25.1.1",
"@atlaskit/button": "^13.4.2",
"@atlaskit/editor-json-transformer": "^8.7.6",
"@atlaskit/editor-wikimarkup-transformer": "^5.7.1",
"@atlaskit/form": "^7.4.1",
"@atlaskit/icon": "^20.1.2",
"@atlaskit/mention": "^21.0.9",
"@atlaskit/section-message": "^6.3.9",
"@atlaskit/spinner": "^14.0.0",
"@atlaskit/textfield": "^3.1.13",
"@atlaskit/tooltip": "^9.0.0",
"@babel/core": "^7.16.0",
"@babel/preset-env": "^7.16.4",
"@babel/preset-react": "^7.16.0",
"@babel/preset-typescript": "^7.16.0",
"@fluentui/react": "^7.137.1",
"@mdx-js/react": "^2.1.2",
"@rollup/plugin-commonjs": "^21.0.1",
"@rollup/plugin-image": "^3.0.2",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-node-resolve": "^13.0.6",
"@rollup/plugin-typescript": "^8.3.0",
"@tanker/file-ponyfill": "^2.22.0",
"@types/lodash-es": "^4.17.6",
"@types/validator": "^13.7.11",
"adf-builder": "^3.3.0",
"axios": "^0.21.1",
"deepmerge": "^4.3.0",
"lodash-es": "^4.17.21",
"moment": "^2.29.1",
"nodemon": "^2.0.19",
"prosemirror-model": "^1.19.0",
"rollup": "^2.60.0",
"rollup-plugin-copy-assets": "^2.0.3",
"rollup-plugin-dts": "^4.0.1",
"rollup-plugin-postcss": "^4.0.1",
"socket.io": "^2.4.1",
"socket.io-client": "^2.3.0",
"typescript": "^4.7.4",
"validator": "^13.6.0",
"react-router-dom": "^5.2.0",
"@types/react-router-dom": "^5.3.3"
},
"peerDependencies": {
"react": "^16.14.0",
"react-dom": "^16.10.2",
"@types/react": "^16.8.22",
"@types/react-dom": "^16.8.4"
},
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"files": [
"dist"
],
"types": "dist/index.d.ts"
}

the following is the package.json for the project creating the error ( note that there is no other reference for react in package.json except the ones in the peerDependecies)

"peerDependencies": {
"@types/react": "^16.8.22",
"@types/react-dom": "^16.8.4",
"react": "^16.14.0",
"react-dom": "^16.10.2"
}

The error is the following

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

in the library package the only hook call i am using is this

import * as React from "react";
import { useEffect } from 'react';
import { HelperClass } from "../common/kits/commonHelpers/HelperClass";
import { Utils } from "../common/kits/commonHelpers/Utils";
import "../common/css/Login.css";
let lang: any = config.otj.defaultLanguage;
export const JiraLogo: React.FC<{}> = ({}) => {

const imageStyle = {
maxWidth: "200px"
};
useEffect(() => {
const userURL = Utils.getUserURL()
lang = HelperClass.getProperty("lang-" + userURL)
});
return (

Creating react/typescript library resulting in Invalid hook call error

{Utils.getUserLanguage("USE_OTJ_TO_CREATE_AND_UPDATE_ISSUES", lang)}

};

the full error below Creating react/typescript library resulting in Invalid hook call error

After testing i tried the following

I added the following class and I only exported it in my library as follow

import * as React from 'react';
import { PrimaryButton, Stack } from '@fluentui/react';
import { DefaultPalette } from '@fluentui/react/lib/Styling';
import "../common/css/UtilsStyle.css";

const stackStyles = {
root: {
background: DefaultPalette.whiteTranslucent40,
padding: 0
},
};
const sectionStackTokens = { childrenGap: 10 };
const headingStackTokens = { childrenGap: 20 };

const LoginFooter = ({ ShowCustomerButton, CustomerButtonClick, disabled, clicked }: any) => {

return (

Hello footer
{ShowCustomerButton} {CustomerButtonClick} {disabled} {clicked}

)
}
export default LoginFooter

This will work in the host application, Although if I edit this functional component and add in the return method any external component for example the following

import * as React from 'react';
import { PrimaryButton, Stack } from '@fluentui/react';
import { DefaultPalette } from '@fluentui/react/lib/Styling';
import "../common/css/UtilsStyle.css";

const stackStyles = {
root: {
background: DefaultPalette.whiteTranslucent40,
padding: 0
},
};
const sectionStackTokens = { childrenGap: 10 };
const headingStackTokens = { childrenGap: 20 };

const LoginFooter = ({ ShowCustomerButton, CustomerButtonClick, disabled, clicked }: any) => {

return (
<Stack className="footer" styles={stackStyles} tokens={

英文:

I am building a react/typescript library using typescript and rollup to export it
this is my package.json for library

     {
      &quot;name&quot;: &quot;infosysta-typescript-core&quot;,
      &quot;version&quot;: &quot;1.0.0&quot;,
      &quot;description&quot;: &quot;This will the infosysta&#39;s core library for typescript&quot;,
      &quot;scripts&quot;: {
        &quot;build_tsc&quot;: &quot;tsc&quot;,
        &quot;build_publish&quot;: &quot;tsc -p .&quot;,
        &quot;publish&quot;: &quot;npm publish&quot;,
        &quot;start&quot;: &quot;tsc &amp;&amp; nodemon build/index.js&quot;,
        &quot;rollup&quot;: &quot;rollup -c&quot;
      },
      &quot;keywords&quot;: [],
      &quot;author&quot;: &quot;Infosysta&quot;,
      &quot;license&quot;: &quot;ISC&quot;,
      &quot;devDependencies&quot;: {
        &quot;@atlaskit/adf-schema&quot;: &quot;^25.1.1&quot;,
        &quot;@atlaskit/button&quot;: &quot;^13.4.2&quot;,
        &quot;@atlaskit/editor-json-transformer&quot;: &quot;^8.7.6&quot;,
        &quot;@atlaskit/editor-wikimarkup-transformer&quot;: &quot;^5.7.1&quot;,
        &quot;@atlaskit/form&quot;: &quot;^7.4.1&quot;,
        &quot;@atlaskit/icon&quot;: &quot;^20.1.2&quot;,
        &quot;@atlaskit/mention&quot;: &quot;^21.0.9&quot;,
        &quot;@atlaskit/section-message&quot;: &quot;^6.3.9&quot;,
        &quot;@atlaskit/spinner&quot;: &quot;^14.0.0&quot;,
        &quot;@atlaskit/textfield&quot;: &quot;^3.1.13&quot;,
        &quot;@atlaskit/tooltip&quot;: &quot;^9.0.0&quot;,
        &quot;@babel/core&quot;: &quot;^7.16.0&quot;,
        &quot;@babel/preset-env&quot;: &quot;^7.16.4&quot;,
        &quot;@babel/preset-react&quot;: &quot;^7.16.0&quot;,
        &quot;@babel/preset-typescript&quot;: &quot;^7.16.0&quot;,
        &quot;@fluentui/react&quot;: &quot;^7.137.1&quot;,
        &quot;@mdx-js/react&quot;: &quot;^2.1.2&quot;,
        &quot;@rollup/plugin-commonjs&quot;: &quot;^21.0.1&quot;,
        &quot;@rollup/plugin-image&quot;: &quot;^3.0.2&quot;,
        &quot;@rollup/plugin-json&quot;: &quot;^6.0.0&quot;,
        &quot;@rollup/plugin-node-resolve&quot;: &quot;^13.0.6&quot;,
        &quot;@rollup/plugin-typescript&quot;: &quot;^8.3.0&quot;,
        &quot;@tanker/file-ponyfill&quot;: &quot;^2.22.0&quot;,
        &quot;@types/lodash-es&quot;: &quot;^4.17.6&quot;,
       
        
        &quot;@types/validator&quot;: &quot;^13.7.11&quot;,
        &quot;adf-builder&quot;: &quot;^3.3.0&quot;,
        &quot;axios&quot;: &quot;^0.21.1&quot;,
        &quot;deepmerge&quot;: &quot;^4.3.0&quot;,
        &quot;lodash-es&quot;: &quot;^4.17.21&quot;,
        &quot;moment&quot;: &quot;^2.29.1&quot;,
        &quot;nodemon&quot;: &quot;^2.0.19&quot;,
        &quot;prosemirror-model&quot;: &quot;^1.19.0&quot;,   
       
        &quot;rollup&quot;: &quot;^2.60.0&quot;,
        &quot;rollup-plugin-copy-assets&quot;: &quot;^2.0.3&quot;,
        &quot;rollup-plugin-dts&quot;: &quot;^4.0.1&quot;,
        &quot;rollup-plugin-postcss&quot;: &quot;^4.0.1&quot;,
        &quot;socket.io&quot;: &quot;^2.4.1&quot;,
        &quot;socket.io-client&quot;: &quot;^2.3.0&quot;,
        &quot;typescript&quot;: &quot;^4.7.4&quot;,
        &quot;validator&quot;: &quot;^13.6.0&quot;,
        &quot;react-router-dom&quot;: &quot;^5.2.0&quot;,
        &quot;@types/react-router-dom&quot;: &quot;^5.3.3&quot;
      },
      &quot;peerDependencies&quot;: {
    &quot;react&quot;: &quot;^16.14.0&quot;,
    &quot;react-dom&quot;: &quot;^16.10.2&quot;,
    &quot;@types/react&quot;: &quot;^16.8.22&quot;,
    &quot;@types/react-dom&quot;: &quot;^16.8.4&quot;
  },
      &quot;main&quot;: &quot;dist/cjs/index.js&quot;,
      &quot;module&quot;: &quot;dist/esm/index.js&quot;,
      &quot;files&quot;: [
        &quot;dist&quot;
      ],
      &quot;types&quot;: &quot;dist/index.d.ts&quot;
    }

the following is the package.json for the project creating the error ( note that there is no other reference for react in package.json except the ones in the peerDependecies)

 &quot;peerDependencies&quot;: {
&quot;@types/react&quot;: &quot;^16.8.22&quot;,
&quot;@types/react-dom&quot;: &quot;^16.8.4&quot;,
&quot;react&quot;: &quot;^16.14.0&quot;,
&quot;react-dom&quot;: &quot;^16.10.2&quot;
 },

The error is the following

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

in the library package the only hook call i am using is this

    import * as React from &quot;react&quot;;
import { useEffect } from &#39;react&#39;;
import { HelperClass } from &quot;../common/kits/commonHelpers/HelperClass&quot;;
import { Utils } from &quot;../common/kits/commonHelpers/Utils&quot;;
import &quot;../common/css/Login.css&quot;;
import config from &quot;../common/data/config/config.json&quot;
let lang :any= config.otj.defaultLanguage;
export const JiraLogo : React.FC&lt;{}&gt; = ({}) =&gt; {
 
  const imageStyle = {
    maxWidth: &quot;200px&quot;
  };
  useEffect(() =&gt; {
    const userURL = Utils.getUserURL()
    lang = HelperClass.getProperty(&quot;lang-&quot; + userURL)
  });
  return (
    &lt;div&gt;
      &lt;div className=&quot;container-div&quot;&gt;
        &lt;img style={imageStyle} src=&quot;../common/data/assets/logo.png&quot; alt=&quot;Connect to Jira&quot; /&gt;
      &lt;/div&gt;
      &lt;div className=&quot;container-div&quot;&gt;
        &lt;p&gt;{Utils.getUserLanguage(&quot;USE_OTJ_TO_CREATE_AND_UPDATE_ISSUES&quot;, lang)}&lt;/p&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
};

the full error below
Creating react/typescript library resulting in Invalid hook call error

After testing i tried the following

I added the following class and I only exported it in my library as follow

import * as React from &#39;react&#39;;
import { PrimaryButton, Stack } from &#39;@fluentui/react&#39;;
import { DefaultPalette } from &#39;@fluentui/react/lib/Styling&#39;;
import &quot;../common/css/UtilsStyle.css&quot;

const stackStyles = {
    root: {
        background: DefaultPalette.whiteTranslucent40,
        padding: 0
    },
};
const sectionStackTokens = { childrenGap: 10 };
const headingStackTokens = { childrenGap: 20 };

const LoginFooter = ({ ShowCustomerButton, CustomerButtonClick, disabled, clicked }: any) =&gt; {

    return (
        &lt;div&gt;
            Hello footer
            {ShowCustomerButton} {CustomerButtonClick} {disabled} {clicked}
        &lt;/div&gt;
       

    )
}
export default LoginFooter

This will work in the host application, Although if I edit this functional component and add in the return method any external component for example the following

    import * as React from &#39;react&#39;;
import { PrimaryButton, Stack } from &#39;@fluentui/react&#39;;
import { DefaultPalette } from &#39;@fluentui/react/lib/Styling&#39;;
import &quot;../common/css/UtilsStyle.css&quot;

const stackStyles = {
    root: {
        background: DefaultPalette.whiteTranslucent40,
        padding: 0
    },
};
const sectionStackTokens = { childrenGap: 10 };
const headingStackTokens = { childrenGap: 20 };

const LoginFooter = ({ ShowCustomerButton, CustomerButtonClick, disabled, clicked }: any) =&gt; {

    return (        
        &lt;Stack className=&quot;footer&quot; styles={stackStyles} tokens={sectionStackTokens}&gt;
            &lt;Stack horizontal disableShrink horizontalAlign=&quot;space-between&quot; tokens={headingStackTokens}&gt;
                &lt;Stack grow&gt;
                    &lt;Stack verticalAlign=&quot;start&quot; &gt;
                        &lt;span&gt;&lt;/span&gt;
                    &lt;/Stack&gt;
                &lt;/Stack&gt;
                &lt;Stack grow&gt;
                    &lt;Stack horizontalAlign=&quot;end&quot; verticalAlign=&quot;end&quot;&gt;
                        &lt;Stack horizontal tokens={headingStackTokens}&gt;
                            {
                                ShowCustomerButton &amp;&amp; (
                                    &lt;PrimaryButton onClick={CustomerButtonClick} text=&quot;Continue as customer&quot; allowDisabledFocus /&gt;
                                )
                            }
                            &lt;PrimaryButton disabled={disabled} onClick={clicked} text=&quot;Continue&quot; allowDisabledFocus /&gt;
                        &lt;/Stack&gt;
                    &lt;/Stack&gt;
                &lt;/Stack&gt;
            &lt;/Stack&gt;
        &lt;/Stack&gt;

    )
}
export default LoginFooter

This will make the error occurred

答案1

得分: 1

以下是翻译好的部分:

我通过将以下内容添加到我的rollup.config.js文件来解决了我的问题:

output:[....],
plugin:[....],
external: ['react', 'react-dom'] // 这一行在这里

而且在我的package.json 文件中,reactreact-dom 应该存在于 peerDependencies 部分:

"peerDependencies": {
  "react": "^16.14.0",
  "react-dom": "^16.14.0"
}
英文:

I fixed my issue by adding this to my rollup.config.js file

  output:[....],
  plugin:[....],
  external: [&#39;react&#39;, &#39;react-dom&#39;] // this line here

and in my package.json react and react-dom should exist in the peerDependecies section

    &quot;peerDependencies&quot;: {
    &quot;react&quot;: &quot;^16.14.0&quot;,
    &quot;react-dom&quot;: &quot;^16.14.0&quot;
   
  },

答案2

得分: 0

以下是代码部分的翻译:

// It's likely one of these is a React Hook and you are calling it from within `useEffect` which would trigger this error.
// 这些中可能有一个是 React Hook,而且你正在在 `useEffect` 中调用它,这可能会触发这个错误。

const userURL = Utils.getUserURL();
// userURL = Utils.getUserURL();

lang = HelperClass.getProperty("lang-" + userURL);
// lang = HelperClass.getProperty("lang-" + userURL);

If those are hooks, they must be imported at the **top** of the **JiraLogo** component as such:
// 如果这些是 Hooks,它们必须像这样在 **JiraLogo** 组件的**顶部**导入:

import * as React from "react";
// import * as React from "react";
import { useEffect } from 'react';
// import { useEffect } from 'react';
import { HelperClass } from "../common/kits/commonHelpers/HelperClass";
// import { HelperClass } from "../common/kits/commonHelpers/HelperClass";
import { Utils } from "../common/kits/commonHelpers/Utils";
// import { Utils } from "../common/kits/commonHelpers/Utils";
import "../common/css/Login.css";
// import "../common/css/Login.css";
import config from "../common/data/config/config.json";
// import config from "../common/data/config/config.json";

export const JiraLogo: React.FC = () => {
  const userURL = Utils.getUserURL();
  // const userURL = Utils.getUserURL();
  let lang: any = HelperClass.getProperty("lang-" + userURL);
  // let lang: any = HelperClass.getProperty("lang-" + userURL);

  const imageStyle = {
    maxWidth: "200px"
  };
  // const imageStyle = {
  //   maxWidth: "200px"
  // };

  return (
    <div>
      <div className="container-div">
        <img style={imageStyle} src="../common/data/assets/logo.png" alt="Connect to Jira" />
      </div>
      <div className="container-div">
        <p>{Utils.getUserLanguage("USE_OTJ_TO_CREATE_AND_UPDATE_ISSUES", lang)}</p>
      </div>
    </div>
  );
};
// return (
//   <div>
//     <div className="container-div">
//       <img style={imageStyle} src="../common/data/assets/logo.png" alt="Connect to Jira" />
//     </div>
//     <div className="container-div">
//       <p>{Utils.getUserLanguage("USE_OTJ_TO_CREATE_AND_UPDATE_ISSUES", lang)}</p>
//     </div>
//   </div>
// );

希望这有所帮助!

英文:

It's likely one of these is a React Hook and you are calling it from within useEffect which would trigger this error.

const userURL = Utils.getUserURL()

lang = HelperClass.getProperty(&quot;lang-&quot; + userURL)

If those are hooks, they must be imported at the top of the JiraLogo component as such:

import * as React from &quot;react&quot;;
import { useEffect } from &#39;react&#39;;
import { HelperClass } from &quot;../common/kits/commonHelpers/HelperClass&quot;;
import { Utils } from &quot;../common/kits/commonHelpers/Utils&quot;;
import &quot;../common/css/Login.css&quot;;
import config from &quot;../common/data/config/config.json&quot;
export const JiraLogo : React.FC = () =&gt; {
const userURL = Utils.getUserURL();
let lang: any = HelperClass.getProperty(&quot;lang-&quot; + userURL);
const imageStyle = {
maxWidth: &quot;200px&quot;
};
return (
&lt;div&gt;
&lt;div className=&quot;container-div&quot;&gt;
&lt;img style={imageStyle} src=&quot;../common/data/assets/logo.png&quot; alt=&quot;Connect to Jira&quot; /&gt;
&lt;/div&gt;
&lt;div className=&quot;container-div&quot;&gt;
&lt;p&gt;{Utils.getUserLanguage(&quot;USE_OTJ_TO_CREATE_AND_UPDATE_ISSUES&quot;, lang)}&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
);
};

There are other triggers for this error but looking at your code that seems most likely.

I hope this helps!

huangapple
  • 本文由 发表于 2023年2月8日 22:11:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定