How to fix "TypeError: Cannot read property 'inherits' of undefined" in React project?

Viewed 1010

I working on React project. I'm trying to use the npm package async-polling (https://www.npmjs.com/package/async-polling), that wants to use the inherits class of the node-utils ; Internally the library has the following lines:

var inherits = hasWindow ? window.nodeUtil.inherits : require('util').inherits;
var EventEmitter = hasWindow ? window.nodeEventEmitter : require('events').EventEmitter;

Of course since the app is running in the browser, hasWindow is true. But there is no nodeUtil or nodeEventEmitter. Therefore I get the error:

TypeError: Cannot read property 'inherits' of undefined

Then I tried adding the util and events package and doing this:

window.nodeUtil = require('util');
window.nodeEventEmitter = require('events');

But I got this error:

TypeError: AsyncPolling is not a constructor

Anther fork was able to fix this issue, but I want to try and stick with the original package, is there a way to fix the issue?

1 Answers

As best I can tell async-polling is an old, unmaintained module that you're better off avoiding. You're running into problems because the module is expecting the presence of two global variables nodeUtil and nodeEventEmitter. It looks like the package is better suited to a node environment and is relying on polyfills in the browser.

I'd suggest finding a more up-to-date package or simply using setInterval to poll.

const intervalInMilliseconds = 5000;
const timerId = setInterval(() => {
  if (/* some condition is met */) {
    clearInterval(timerId);
  } else {
    // do stuff
  }
}, intervalInMilliseconds);
Related