First of all link to the repo: https://github.com/vmarchesin/react-konami-code
You should be able to build it (make sure to uncomment the export on src/index.js) and link to your project. It is also possible to try it out using npm i -S react-konami-code@2.0.0-beta.0 and get the error for the hook. I removed the hook from 2.0.0-beta.1 because it's broken.
Description of the problem
I created a custom hook for my npm module and it doesn't work after being published or using it as a module. I suspect the issue is with how webpack bundles it but I can't solve it.
Steps taken
- I made sure to declare
reactandreact-domas externals in my webpack config.
externals: [
{
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom',
},
},
],
- Declared
reactandreact-domaspeerDependenciesin thepackage.json
"peerDependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
- The hook is working. If I declare it and use it, it works. If I import it from the module (or use npm link) it doesn't. Here is the code for the hook:
import { useEffect, useState, useCallback } from 'react';
export default (action, {
code = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65],
} = {}) => {
const [input, setInput] = useState([]);
const onKeyUp = useCallback(
(e) => {
const newInput = input;
newInput.push(e.keyCode);
newInput.splice(-code.length - 1, input.length - code.length);
setInput(newInput);
if (newInput.join('').includes(code.join(''))) {
action();
}
},
[input, setInput, code, action],
);
useEffect(() => {
document.addEventListener('keyup', onKeyUp);
return () => {
document.removeEventListener('keyup', onKeyUp);
};
}, [onKeyUp]);
};
- I am not calling the hook inside a class component.
I am using webpack@4.43.0 as well as babel@7 and babel-loader@8.1.0.
Here is how I export the index file for the webpack build:
import Konami from './Konami';
export default Konami; // disregard this, it works
export { default as useKonami } from './useKonami'; // this doesn't work
Here's a screenshot and transcript of the error:
Unhandled Runtime Error 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:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app