0

I have this class in my React project:

utils.ts

export class BtnManager {
  private setState: Function

  constructor(setState: React.Dispatch<React.SetStateAction<IBtnProps>>) {
    this.setState = setState;

  }

  public updateBtn(text?: string, disabled?: boolean, rest?: IBtnProps) {
    if (!rest) rest = INITIAL_BUTTON_STATE;
    if (text && disabled) {
      this.setState({
        ...rest,
        text,
        disabled,
      });
    } else {
      this.setState(rest);
    }
  }
}

And this useEffect in a component

Stake.tsx

useEffect(() => {
  const btnManager = new BtnManager(setBtnProps);
  const updateBtn = btnManager.updateBtn
    if (!accountId) {
      updateBtn();
    } else if (!tokenOut.info) {
      updateBtn('Select a Pool', true);
    }

 }, [accountId, tokenOut.info]
}

But am getting this error in the browser console:

Uncaught TypeError: Cannot read properties of undefined (reading 'setState')

I pass setState functions to components all the time, but this is the first time I am trying to create a class for helping manage state.I can console log this.setState inside the constructor after I initialize it and it logs the function signature, but when its used in the updateBtn method through the useEffect the above error is thrown. Not sure what is going on here, any insight appreciated.

  • 1
    `updateBtn` makes use of `this` and since you detached it from the instance of the class, you've made `this` `undefined`. – Quentin Jun 29 '22 at 21:46
  • The problem is not with passing `setState` to the class, the problem is calling a standalone function `updateBtn(…)` instead of a method `btnManager.updateBtn(…)`. If you really want to do that for some reason, you'll need to `.bind()` the method to the `btnManager` instance. – Bergi Jun 29 '22 at 21:49

0 Answers0