0

I'm trying to update to update the window state whenever the App component mounts. With the below code, I receive an Error in response to tabs.query: TypeError: this.addTabs is not a function.

I don't understand why this.addTabs is not considered a function, as the function is above the reference to this.addTabs(tabs), and I think it was correctly bound.

class App extends Component {
 constructor(props){
  super(props);
  this.state = {
     window: []
  };
  this.addTabs = this.addTabs.bind(this);
}

addTabs(tabs){
  this.setState({window:this.state.window.concat(tabs)});
};

componentDidMount(){
  chrome.tabs.query({active:true},function(tabs){
    this.addTabs(tabs);
});

I'm not looking to use the arrow function. I looked at similar questions, and the response was to bind the function in the constructor, which I believe I did. Any help or pointers would be appreciated!

3
  • 2
    If you dont use arrow function, you are actually referring to the function context when you use ‘this.addTabs(tabs), otherway is to you can define ‘_this = this’ inside componentDidMount and use _this.addTabs Commented Dec 23, 2018 at 16:03
  • Thanks @AaminKhan - that solved it. I should probably read up on JS function context. Cheers Commented Dec 23, 2018 at 16:12
  • 1
    Cheers my friend, happy hacking! Commented Dec 23, 2018 at 16:14

1 Answer 1

4

Your issue is in this block:

componentDidMount(){
  chrome.tabs.query({active:true},function(tabs){
    this.addTabs(tabs);
  });
}

Inside your callback, the context is different so this refers to another context.

You have several ways to fix it.

1) Assign the ref to this outside the callback and use that ref:

componentDidMount(){
  const that = this;
  chrome.tabs.query({active:true},function(tabs){
    that.addTabs(tabs);
  });
}

2) Bind the current this to the callback:

componentDidMount(){
  chrome.tabs.query({active:true},(function(tabs){
    this.addTabs(tabs);
  }).bind(this));
}

3) Use an arrow function:

componentDidMount(){
  chrome.tabs.query({active:true}, (tabs) => {
    this.addTabs(tabs);
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a ton! Super helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.