-1

My error: Uncaught TypeError: Cannot read property 'verified' of undefined at checkForVerifiedStatus

Part of my code:

export default class Verification extends React.Component {
  state = {
    verified: false
  };

  verify = () => {
    this.setState({ verified: true });
  };

  shouldComponentUpdate() {
    return false;
  }

  render() {
    let timer = setInterval(checkForVerifiedStatus, 200);
    function checkForVerifiedStatus() {
      if (!uiStore.login.verified) return;
      else {
        this.verify;
        clearInterval(timer);
        console.log('verified ' + this.state.verified)
        return;
      }
    }

It seems like this.state.verified is not able to read the state value.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
shaviq
  • 35
  • 5
  • 2
    Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Emile Bergeron Feb 23 '20 at 17:35
  • 3
    TL;DR `function` has its own context (`this`) which, in this case, is not the component, so `this.state` returns `undefined` throwing the error when trying to access `verified` on it. – Emile Bergeron Feb 23 '20 at 17:37
  • 1
    `uiStore.login` is undefined. What should it be? – Jackson Feb 23 '20 at 17:37
  • Is the error happening with `this.state.verified` or `uiStore.login.verified`? It's not clear from your post. – Chris Farmer Feb 23 '20 at 18:01

1 Answers1

1

just change

function checkForVerifiedStatus() {
// some code here
}

to

const checkForVerifiedStatus = () => {
// some code here
}

what's happening here is the declaration of your checkForVerifiedStatus has its own context which when you call this would refer to the function itself, not the parent react class hence turning it into a arrow function automatically binds the context to the parent level which is your react component when refering to this


Lelouch
  • 910
  • 6
  • 19