title: How to use React hook in a react class?
body: <p>As a newbie in JS world i am in a big trouble ...
  I am using a react hook</p>
  <pre><code>import { useKeycloak } from '@react-keycloak/web';
  import { useCallback } from 'react';
  export const useAuthenticatedCallback = (callbackFn) =&gt; {
      const [keycloak, initialized] = useKeycloak()
    
      const authCallback = useCallback(() =&gt; {
        // Do nothing while Keycloak is initializing
        if (!initialized) {
          return
        }
    
        // if user is not authenticated redirect to login
        if (!keycloak.authenticated) {
          return keycloak.login()
        }
    
        // otherwise invoke function
        return callbackFn()
      }, [callbackFn, initialized, keycloak])
    
      return authCallback
    }
  </code></pre>
  <p>and able to use inside a function</p>
  <pre><code>import React from &quot;react&quot;;
  import {Grid, Avatar, Chip } from '@material-ui/core';
  import { useAuthenticatedCallback } from '../../shared/keycloak/KeycloakOnDemand'
  // Tranding function component
  function Tranding(props) {
    const yourCallback = () =&gt; {
      // The code you need to be authenticated to run
      return yourCallback;
     };
    const authenticatedCallback = useAuthenticatedCallback(yourCallback);
    return (
      &lt;Grid container spacing={3}&gt;
          &lt;Grid className=&quot;text-center&quot; item  sm={12} xs={12} md={2}&gt;
              &lt;h4&gt;Trending..&lt;/h4&gt;
          &lt;/Grid&gt;
          &lt;Grid item md={10}&gt;
              &lt;div className=&quot;trending-container&quot;&gt;
              &lt;button onClick={authenticatedCallback} label=&quot;ClickMe&quot;/&gt;
                   
              &lt;/div&gt;
          &lt;/Grid&gt;
      &lt;/Grid&gt;
    );
  }
  
  // export the component.
  export default Tranding;
  </code></pre>
  <p>Upto here everything fine and things are working according to requirement.</p>
  <p>Now i got a challenge to use same hook  inside a react component class ,but fail to achieve this ..Can anyone help for this issue?</p>
  <p>I was trying to use in this class</p>
  <pre><code>import React from &quot;react&quot;;
  import {connect} from 'react-redux';
  import PostList from &quot;./PostList&quot;;
  import Grid from '@material-ui/core/Grid';
  import Switch from '@material-ui/core/Switch';
  import Card from '@material-ui/core/Card';
  import CardContent from '@material-ui/core/CardContent';
  import Autocomplete from '@material-ui/lab/Autocomplete';
  import { TextField, ButtonGroup, Button  } from '@material-ui/core';
  import SaveIcon from '@material-ui/icons/Save';
  import TextEditor from './TextEditor';
  //import CKTextEditor from '../../shared/CKTextEditor';
  import {NotificationContainer, NotificationManager} from 'react-notifications';
  import CircularSpinner from '../../shared/CircularSpinner';
  
  import postService from '../../services/PostService';
  
  class Posts extends React.Component {
      constructor() {
          super()
          this.state = {
              posts: [],
              totalPages: 0,
              isLoading: false,
              postForm: {
                  isValidationActive: false,
                  tradeTypeId: 1,
                  tradeTypeText: 'Buy',
                  price: '', priceValid: false,
                  stopLoss: '', stopLossValid: false,
                  targetPrice: '', targetPriceValid: false,
                  targetDate: '', targetDateValid: false,
                  title: '',
                  notes: '', notesValid: false
              },
              analysisForm: {
                  isValidationActive: false,
                  title: '', titleValid: false,
                  notes: '', notesTemp:'', notesValid: false
              },      
              isTradeCallActive: true,
              tradeCallFormValid: false,
              analysisFormValid: false,
              companyCode: '',
              companyValid: false,
              postTypes: [],
              tradeCallTypes: [],
              companies: [],
              tradeTypeSelected: 'Buy'
          };
          this.formRef = null;
  
          this.handleChange = this.handleChange.bind(this);
          this.onCompanyCodeChange = this.onCompanyCodeChange.bind(this);
          this.handleEditorChange = this.handleEditorChange.bind(this);
          this.handleTradeCallSubmit = this.handleTradeCallSubmit.bind(this);
          this.handleAnalysisSubmit = this.handleAnalysisSubmit.bind(this);
          this.loadFormModel = this.loadFormModel.bind(this);
          this.clearTradeCallForm = this.clearTradeCallForm.bind(this);
          this.clearAnalysisForm = this.clearAnalysisForm.bind(this);
          this.loadPosts = this.loadPosts.bind(this);
      }
  
      
      // handle chnage events for all controls.
      handleChange(event) {   
          let _postForm = this.state.postForm;
          let _isTradeCallActive = this.state.isTradeCallActive; 
          let _targetValue = event.target.value; 
          let _companyValid = this.state.companyValid;
          let _companyCode = this.state.companyCode; 
  
          if(event.target.name === 'TradeCall' || event.target.name === 'Analysis'){           
              if(event.target.name === 'Analysis' &amp;&amp; event.target.checked) {_isTradeCallActive = false;}
              if(event.target.name === 'TradeCall' &amp;&amp; event.target.checked) {_isTradeCallActive = true;}
          }
  
          if(event.target.name === 'txtCompany') {            
              _companyCode = _targetValue;
              if (_targetValue.length &lt; 3) { _companyValid = false; }
          }
  
          if(event.target.name === 'txtTitle'){
              let _analysisForm = this.state.analysisForm;
              _analysisForm.titleValid = true; 
              _analysisForm.title = _targetValue;
              if (_targetValue.length &lt; 10) { _analysisForm.titleValid = false; }
  
              let _analysisFormValid = false;
              if(_analysisForm.titleValid &amp;&amp; _analysisForm.notesValid) {
                  _analysisFormValid = true;
              }
      
              this.setState({ ...this.state, analysisForm: _analysisForm, analysisFormValid: _analysisFormValid});
              return;
          }
  
          if(event.target.name === 'txtPrice'
              || event.target.name === 'txtStoploss'
              || event.target.name === 'txtTarget'
              || event.target.name === 'notesTextArea'
              || event.target.name === 'targetDate'
              || event.target.name === 'selectTradeType'){
                  
                  if(event.target.name === 'txtPrice') {
                      _postForm.priceValid = true;
                      _postForm.price = _targetValue;
                      if (_targetValue.length &lt; 1 || _targetValue &lt; 1) { _postForm.priceValid = false; }
                  }
                  if(event.target.name === 'txtStoploss') {
                      _postForm.stopLossValid = true;
                      _postForm.stopLoss = _targetValue;
                      if (_targetValue.length &lt; 1 || _targetValue &lt; 1) { _postForm.stopLossValid = false; }
                  }
                  if(event.target.name === 'txtTarget') {
                      _postForm.targetPriceValid = true;
                      _postForm.targetPrice = _targetValue;
                      if (_targetValue.length &lt; 1 || _targetValue &lt; 1) { _postForm.targetPriceValid = false; }
                  }
                  if(event.target.name === 'notesTextArea') {
                      _postForm.notesValid = true; 
                      _postForm.notes = _targetValue;
                      if (_targetValue.length &lt; 20) { _postForm.notesValid = false; }
                  }
                  if(event.target.name === 'targetDate') {
                      _postForm.targetDateValid = true; 
                      _postForm.targetDate = _targetValue;
                      if (_targetValue.length &lt; 8) { _postForm.targetDateValid = false; }
                  }
          }
  
          let _tradeType = this.state.tradeCallTypes.find(x =&gt; x.Name === this.state.tradeTypeSelected)
          _postForm.tradeTypeId = _tradeType.Id;
          _postForm.tradeTypeText = _tradeType.Name; 
          
          let _tradeCallFormValid = false;
          if(this.state.companyValid &amp;&amp; _postForm.priceValid &amp;&amp; _postForm.stopLossValid &amp;&amp; _postForm.targetPriceValid &amp;&amp; _postForm.targetDateValid &amp;&amp; _postForm.notesValid) {
              _tradeCallFormValid = true;
              _postForm.title = `${_postForm.tradeTypeText} ${this.state.companyCode} at price ${_postForm.price} for target ${_postForm.targetPrice} by date ${_postForm.targetDate} with SL ${_postForm.stopLoss}`; 
          }
  
          this.setState({ ...this.state, postForm: _postForm, tradeCallFormValid: _tradeCallFormValid, isTradeCallActive: _isTradeCallActive, companyValid: _companyValid, companyCode: _companyCode });
      };
  
       
  
       
      // handle trade call submit click.
      handleTradeCallSubmit(){
         
          if(this.state.tradeCallFormValid){
              // To DO
              this.setState({ ...this.state, tradeCallFormValid: false});
              let _postForm = this.state.postForm;
              let _companyCode = this.state.companyCode;
  
              let requestBody = {
                  eventType:'create-trade-call-post', 
                  callType:_postForm.tradeTypeId,
                  symbol:_companyCode,
                  userId: this.props.activeUser.Id,
                  price:_postForm.price,
                  stopLoss:_postForm.stopLoss,
                  targetPrice:_postForm.targetPrice,
                  targetDate:_postForm.targetDate,
                  tags: _companyCode,
                  title:_postForm.title,
                  notes:_postForm.notes
              }
          
              postService.create(requestBody)
                  .then((result) =&gt; {
                      NotificationManager.success(`Trade call post created successfully...`);
                      this.loadPosts(1);
                      this.clearTradeCallForm();
                  }).catch((error) =&gt; {
                      NotificationManager.error(`Trade call post creation failed..`);
                      console.log(`Error: ${error}`);
                  });
          } else {
              let _postForm = this.state.postForm;
              _postForm.isValidationActive = true;
              this.setState({ ...this.state, postForm: _postForm});
          }
          
      }
  
     
      // component did mount event called after the virtual DOM loaded. 
      componentDidMount() {
          this.setState({ ...this.state, isLoading: true });
          this.loadFormModel();
      }
  
      render() {
          if (this.state.isLoading) {
              return &lt;CircularSpinner /&gt;;
          }
  
          return ( 
          &lt;div&gt;
              &lt;NotificationContainer/&gt;
              &lt;Card&gt;
                  &lt;CardContent&gt;
                      &lt;form ref={(ref) =&gt; this.formRef = ref} noValidate autoComplete=&quot;off&quot;&gt;
                          &lt;Grid className=&quot;text-center&quot; container spacing={2}&gt;
                          {
                              this.state.postTypes.map((postType, index) =&gt; 
                                  &lt;Grid key={postType.Id} item sm={6} xs={6} md={3}&gt;
                                      &lt;h5&gt;{postType.Name} &lt;Switch  key={postType.Id}  checked={(postType.Name === 'TradeCall')?this.state.isTradeCallActive: !this.state.isTradeCallActive} value={postType.Id} onChange={this.handleChange} name={postType.Name} inputProps={(postType.Name === 'TradeCall') ? {'aria-label': 'secondary checkbox' }: { 'aria-label': 'primary checkbox' }} /&gt;&lt;/h5&gt;
                                  &lt;/Grid&gt;
                              )                            
                          }
                              &lt;Grid item sm={12} xs={12} md={6}&gt;
                                  &lt;Autocomplete
                                      id=&quot;companyAutocomplete&quot;
                                      options={this.state.companies}
                                      getOptionLabel={(option) =&gt; option.Symbol}
                                      onInputChange={this.onCompanyCodeChange}  
                                      fullWidth
                                      renderInput={(params) =&gt; &lt;TextField fullWidth id=&quot;txtCompany&quot; {...params} 
                                      error={((this.state.postForm.isValidationActive || this.state.analysisForm.isValidationActive)) 
                                          &amp;&amp; !this.state.companyValid} name=&quot;txtCompany&quot; size=&quot;small&quot; label=&quot;Company&quot; onChange={this.handleChange} variant=&quot;outlined&quot; placeholder=&quot;Company..&quot;  /&gt;}
                                  /&gt;
                              &lt;/Grid&gt;
                          &lt;/Grid&gt;
                          &lt;div className={!this.state.isTradeCallActive ? 'hidden' : ''}&gt;
                              &lt;Grid container spacing={2}&gt;
                                  &lt;Grid item sm={12} xs={12} md={2}&gt;
                                      &lt;ButtonGroup fullWidth aria-label=&quot;small button group&quot;&gt;
                                          &lt;Button onClick={()=&gt;{this.setState({ ...this.state, tradeTypeSelected: &quot;Sale&quot;})}}
                                              variant={(this.state.tradeTypeSelected === &quot;Buy&quot;) ? &quot;outlined&quot; : &quot;contained&quot;} 
                                              color={(this.state.tradeTypeSelected === &quot;Buy&quot;) ? &quot;default&quot; : &quot;secondary&quot;}&gt; Sale
                                          &lt;/Button&gt;
                                          &lt;Button onClick={()=&gt;{this.setState({ ...this.state, tradeTypeSelected: &quot;Buy&quot;})}} 
                                              variant={(this.state.tradeTypeSelected === &quot;Buy&quot;) ? &quot;contained&quot; : &quot;outlined&quot;} 
                                              color={(this.state.tradeTypeSelected === &quot;Buy&quot;) ? &quot;secondary&quot; : &quot;default&quot;}&gt; Buy
                                          &lt;/Button&gt;
                                      &lt;/ButtonGroup&gt;
                                  &lt;/Grid&gt;
                                  &lt;Grid item sm={12} xs={12} md={2}&gt;
                                      &lt;TextField fullWidth id=&quot;txtPrice&quot; error={this.state.postForm.isValidationActive &amp;&amp; !this.state.postForm.priceValid} name=&quot;txtPrice&quot; type=&quot;number&quot; InputProps={{ inputProps: { min: 0} }} size=&quot;small&quot; label=&quot;Price&quot; onChange={this.handleChange} variant=&quot;outlined&quot; placeholder=&quot;Price..&quot;  /&gt;
                                  &lt;/Grid&gt;
                                  &lt;Grid item sm={12} xs={12} md={2}&gt;
                                      &lt;TextField fullWidth id=&quot;txtStoploss&quot; error={this.state.postForm.isValidationActive &amp;&amp; !this.state.postForm.stopLossValid} name=&quot;txtStoploss&quot; type=&quot;number&quot; InputProps={{ inputProps: { min: 0} }}  size=&quot;small&quot; label=&quot;Stoploss&quot; onChange={this.handleChange} variant=&quot;outlined&quot; placeholder=&quot;SL..&quot;  /&gt;
                                  &lt;/Grid&gt;
                                  &lt;Grid item sm={12} xs={12} md={2}&gt;
                                      &lt;TextField fullWidth id=&quot;txtTarget&quot; error={this.state.postForm.isValidationActive &amp;&amp; !this.state.postForm.targetPriceValid} name=&quot;txtTarget&quot; type=&quot;number&quot; InputProps={{ inputProps: { min: 0} }}  size=&quot;small&quot; label=&quot;Target price&quot; onChange={this.handleChange} variant=&quot;outlined&quot; placeholder=&quot;Price..&quot;  /&gt;
                                  &lt;/Grid&gt;
                                  &lt;Grid item sm={12} xs={12} md={4}&gt;
                                      &lt;TextField fullWidth id=&quot;targetDate&quot; error={this.state.postForm.isValidationActive &amp;&amp; !this.state.postForm.targetDateValid} name=&quot;targetDate&quot; onChange={this.handleChange} type=&quot;date&quot; size=&quot;small&quot; label=&quot;Target date&quot; variant=&quot;outlined&quot;  InputLabelProps={{ shrink: true, }} /&gt;
                                  &lt;/Grid&gt;
                              &lt;/Grid&gt;
                              &lt;Grid container spacing={2}&gt;                                
                                  &lt;Grid item sm={12} xs={12} md={12}&gt;
                                      &lt;TextField id=&quot;notesTextArea&quot; error={this.state.postForm.isValidationActive &amp;&amp; !this.state.postForm.notesValid} name=&quot;notesTextArea&quot; onChange={this.handleChange} size=&quot;medium&quot; fullWidth 
                                          placeholder=&quot;Enter notes here..&quot; variant=&quot;outlined&quot; label=&quot;Notes&quot;
                                          multiline rows={3} rowsMax={4} /&gt;
                                  &lt;/Grid&gt;
                              &lt;/Grid&gt;
                              &lt;Grid justify=&quot;center&quot;  container spacing={2}&gt;
                                  &lt;Grid item sm={12} xs={12} md={3}&gt;
                                      &lt;Button size=&quot;medium&quot; fullWidth id=&quot;btnSubmit&quot; startIcon={&lt;SaveIcon /&gt;} onClick={this.handleTradeCallSubmit} variant=&quot;contained&quot; color=&quot;primary&quot;&gt; Save &lt;/Button&gt;
                                  &lt;/Grid&gt;
                              &lt;/Grid&gt;
                          &lt;/div&gt;
                          
                      &lt;/form&gt;
                  &lt;/CardContent&gt;
              &lt;/Card&gt;
              &lt;Grid container spacing={3}&gt;
                  &lt;Grid item md={12}&gt;                    
                      &lt;PostList totalPages={this.state.totalPages} posts={this.state.posts} loadPosts={this.loadPosts} /&gt;
                  &lt;/Grid&gt;
              &lt;/Grid&gt;
          &lt;/div&gt;
        )
      }
    } 
  
  // Map redux state to props
  const mapStateToProps = state =&gt; ({
      activeUser: state.session.activeUser
    });
    
  // export the component.
  export default connect(mapStateToProps)(Posts);
  </code></pre>
  <p>So before calling <code>handleTradeCallSubmit()</code> method i want to check user is login or not if not login redirect to login page otherwise process the method?</p>