Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected 'this' to be used by class method

In my class, eslint is complaining "Expected 'this' to be used by class method 'getUrlParams'

Here is my class:

class PostSearch extends React.Component {   constructor(props) {     super(props);     this.getSearchResults();   }    getUrlParams(queryString) {     const hashes = queryString.slice(queryString.indexOf('?') + 1).split('&');     const params = {};      hashes.forEach((hash) => {       const [key, val] = hash.split('=');       params[key] = decodeURIComponent(val);     });      return params;   }    getSearchResults() {     const { terms, category } = this.getUrlParams(this.props.location.search);     this.props.dispatch(Actions.fetchPostsSearchResults(terms, category));   }    render() {     return (       <div>         <HorizontalLine />         <div className="container">           <Col md={9} xs={12}>             <h1 className="aboutHeader">Test</h1>           </Col>           <Col md={3} xs={12}>             <SideBar />           </Col>         </div>       </div>     );   } } 

What is the best approach to solve this or refactor this component?

like image 844
Hinesh Patel Avatar asked May 29 '17 19:05

Hinesh Patel


People also ask

How do you fix expected this to be used by class method?

To fix the Expected 'this' to be used by class method error with JavaScript, we should change the function causing the error to an arrow function. const getUrlParams = (queryString) => { //... }; to define the getUrlParams as an arrow function. Then if it doesn't reference this , then the error would go away.

How do you call a class method in JavaScript?

The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

What are static methods in JavaScript?

Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.


1 Answers

you should bind the function to this as the ESLint error says "Expected 'this' to be used by class method 'getUrlParams'

getUrlParams = (queryString) => { .... } 

as you are not using getUrlParams during render (like onClick()) so the above technique is good which we can call it "usage of arrow function in class property".

there are other ways of binding too:

  • binding in constructor this.getUrlParams=this.getUrlParams.bind(this)
  • arrow function in render e.g.onClick={()=>this.getUrlParams()} assumed that function does not have params.
  • and React.createClass which with ES6 does not make sense :)
like image 51
Amir-Mousavi Avatar answered Oct 07 '22 07:10

Amir-Mousavi