LoginSignup
0
0

More than 1 year has passed since last update.

RailsAPI+Reactでnpmの階層を間違えて沼った話

Posted at

ブラウザのコンソールに以下のエラーが出た

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:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

1と2には該当していなかったので、3に当たりをつけてnpm lsnpm ls reactなどをしてみる。
npm ls reactではエラーが発生しているが解決方法がわからず、とりあえず
「node_modulesを削除」→「再度npm install」をしてみるも解決せず。。

ただ、あることに気づきます。

node_modulesが二つあるぞ。。?

私はRailsAPI+Reactでアプリを作っていたので、
ルートディレクトリは基本Rails関連で埋め尽くされていて、frontend/のみにreact関連のディレクトリやファイル(node_modulesやpackage.jsonなど)が存在する想定だった。

期待していたディレクトリ構成↓

$ ls
Gemfile       README.md     app/          config/       db/           lib/          public/       test/         vendor/
Gemfile.lock  Rakefile      bin/          config.ru     frontend/     log/          storage/      tmp/

しかし、実際にlsしてみると上記+でnode_modules/,package-lock.json,package.jsonが存在していた!!

どうやらnpm install 〇〇をfrontend/に入って実行しなければいけないのに、その一個上のルートディレクトリで行っていたことが原因のようだった。

解決方法

ルートディレクトリのnode_modules/,package-lock.json,package.jsonを全て削除し(node_modulesだけで良いかもしれない)、再度npm startしたらエラーが治った!!

$ rm -rf node_modules
$ rm package-lock.json
$ rm package.json
$ npm startとしていたタブでControll+Cしていったん終了
$ npm start

ただ、機能自体は問題なくなったのだが、npm ls reactしたらまだエラーが出るのが気がかり。。
どなたかご存知の方、教えてください〜

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0