1

I have a Node server with a utils file that looks like this:

update = () => {
//
};
module.exports = { update };

This works, but when I use the same file in a React app, I get the error

"'update' is not defined  no-undef"

To fix this I must add const keyword. This makes no sense to me. Why is declaring the function needed only in React?

seventeen
  • 557
  • 1
  • 6
  • 21

1 Answers1

1

This is because the React you're using has come bundled with a linter which warns you of potential code quality problems. create-react-app is one of the React bundles which comes integrated with ESLint.

If you don't want to see the warning and don't want to use ESLint, you can build your project manually from scratch, rather than using a boilerplate setup like create-react-app.

If you installed ESLint for your Node project, you'd see the no-undef warning for Node code as well.

Note that what you're seeing is a linter warning, not a runtime error. If you ignore the warning and bundle and serve the project anyway, it will be still be runnable if it doesn't run in strict mode. (In strict mode, the use of an undefined variable without declaring it with const / let / var first will throw an error)

The linting rule being violated in the code is described at length here:

https://eslint.org/docs/rules/no-undef

For further reference on what's going on when you don't declare a variable (and why it probably isn't a good idea), see What is the purpose of the var keyword and when should I use it (or omit it)?

If you're using modules, you should pretty much always be using explicit imports and exports only - don't implicitly create global variables (like you're currently doing with update = () => {), since that defeats the point of using modules.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320