0

I want to setState in a static function. But I got an error which says setState is not a function:

export default class SearchTab extends React.Component {
          constructor(props) {
            super(props);
            this.state = {
              name: ''
            }
          }

          static callingFun = () => {
            this.setState({ name:'ali' })
          }
        }
1
  • 1
    You have XY problem. Why is callingFun static? Commented Nov 6, 2018 at 7:48

2 Answers 2

1

You cannot use this.setState in a static method.Because if you use static function then a static method won't be able to access 'this' inside that function. Please refer https://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx

Sign up to request clarification or add additional context in comments.

Comments

0

Statics don't have instances. They are basically shared between classes and this won't work in it. You should make your function a class function instead

1 Comment

can you give me simple example that will help

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.