5

I'm trying to build a little chat bot, and I seem to be nearing completion if it were not for this bug. The issue seems to be that my switch statement isn't handling the setState properly.

Uquestion extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: this.props.text, 
      response: "Here is the answer"
    }

    this.handleChange = this.handleChange.bind(this)

    this.key = this.key.bind(this)

    this.fetchResponse = this.fetchResponse.bind(this)
  }


  handleChange(event) {
    this.setState({
      question: event.target.value
    })
  }

  fetchResponse() {
    switch(this.state.searchKey) {
      case "BBQ": 
        this.setState({
          response:"Texas BBQ" 
        })
      break; 
      case "book": 
        this.setState({
          response:"It's close, but probably The Night in Question by Tobias Wolff." 
        })
      break;
      case "restaurant": 
        this.setState({
          response:"Andaman, a little Thai spot in Denton, Texas." 
        })
      break;
      case "work": 
        this.setState({
          response:"Lots of this and lots of that." 
        })
      break;
      case "upbringing": 
        this.setState({
          response:"Texas thunderstorms over endless plains." 
        })
      break;
      case "future": 
        this.setState({
          response:"I hope to work on meaningful applications and write meaningful narratives" 
        })
      break;
      case "fun": 
        this.setState({
          response:"When the moon is full, I write by candle light." 
        })
      break;
      default: 
        this.setState({
          response:"Um, what?" 
        })
    }
  }

  //this function sets a key that I will later use to fetch a response to the user's question.
  key() {
    var question=this.state.question; 
    var questionUpper=question.toUpperCase();  

    // the is not -1 determines if the phrase appears anywhere in the question.
    if(questionUpper.search("FAVORITE FOOD")!==-1) {
      this.setState({
        searchKey:"BBQ" 
      }, this.fetchResponse())
    } 
    else if(questionUpper.search("FAVORITE BOOK")!==-1) {
      this.setState({
        searchKey:"Book" 
      }, this.fetchResponse())
    } 
    else if(questionUpper.search("FAVORITE RESTAURANT")!==-1) {  
      this.setState({
        searchKey:"Restaurant" 
      },this.fetchResponse())
    } 
    else if(questionUpper.search("WORK EXPERIENCE")!==-1) {
      this.setState({
        searchKey:"work" 
      },this.fetchResponse())
    } 
    else if(questionUpper.search("GROWING UP")!==-1) {
      this.setState({
        searchKey:"upbringing" 
      },this.fetchResponse())
    } 
    else if(questionUpper.search("FAVORITE AUTHOR")!==-1) {
      this.setState({
        searchKey:"author" 
      },this.fetchResponse())
    } 
    else if(questionUpper.search("FUTURE")!==-1) {
      this.setState({
        searchKey:"future" 
      },this.fetchResponse())
    } 
    else if (questionUpper.search("FOR FUN")!==-1) {
      this.setState({
        searchKey:"fun" 
      },this.fetchResponse())
    }
    else {
      this.setState({
        searchKey:"default" 
      }, this.fetchResponse())
    }
  } 

  render() {
    return (
      <div> 
        <p> {this.state.response} </p> 
        <textarea onChange = {this.handleChange} className="q">       {this.props.text} </textarea> 
        <button className="a" onClick={this.key}>Ask!</button> 
      </div>
    );
  }
}
ReactDOM.render(<Uquestion text="Type Question Here."/>,      document.getElementById("content"))
5
  • What do you mean by "isn't handle the setState properly"? What is going wrong?
    – Ben Hare
    Commented Jul 22, 2016 at 4:38
  • Hey Ben, So when I ask "What is your favorite food?" response changes to the default in the UI. Then, if I click the ask button again, response gets updated correctly in the UI. However, after this, the ask button prompts no changes. I'm lead to believe that this is an issue with setState, particularly as it appears in the switch block. I'm really not sure though. I'm a beginner. Commented Jul 22, 2016 at 4:54
  • Here is the codepen: codepen.io/WriterState/pen/xOAApB Commented Jul 22, 2016 at 4:55
  • I only have one question: Why are you writing a chat bot in a UI library?
    – Dan
    Commented Jul 22, 2016 at 8:15
  • React is the only framework I have a decent grasp of. What would be a better alternative? Commented Jul 22, 2016 at 17:01

2 Answers 2

1

You are passing wrong callback in setState function. And in fetchResponse you've wrote some wrong cases. I've corrected your mistakes, you can see on working example in Codepen

wrong:

this.setState({
  searchKey: "book"
}, this.fetchResponse())

correct:

this.setState({
  searchKey: "book"
}, this.fetchResponse)
2
  • Dang, this is somewhat embarrassing, what with those mismatched cases! Thank you for this solution. This is about the extent of my React abilities. Do you suggest a follow up project? Thank you so much! Commented Jul 22, 2016 at 6:49
  • you are welcome) click to accept my answer if it solved your problem ) and if you have another questions - I will always glad to help Commented Jul 22, 2016 at 7:01
-1

you can read react source code

ReactComponent.prototype.setState = function (partialState, callback){
  !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state  variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0;
  this.updater.enqueueSetState(this, partialState);
  if (callback) {
    this.updater.enqueueCallback(this, callback, 'setState');
  }
};

enqueueCallback: function (publicInstance, callback, callerName) {
  ReactUpdateQueue.validateCallback(callback, callerName);
  var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);

  if (!internalInstance) {
    return null;
  }

  if (internalInstance._pendingCallbacks) {
    internalInstance._pendingCallbacks.push(callback);
  } else {
    internalInstance._pendingCallbacks = [callback];
  }

  enqueueUpdate(internalInstance);
}

function enqueueUpdate(internalInstance) {
  ReactUpdates.enqueueUpdate(internalInstance);
}

so, I think you the callback is like this:

this.setState({
  searchKey:"BBQ" 
}, this.fetchResponse)
3
  • That's looking pretty incomprehensible lol, but is this the actual flow for what happens with setState? Commented Jul 22, 2016 at 7:14
  • yeah! this is what happen the react use setState. maybe I should put more code. I think react source code is not incomprehensible in some case. Commented Jul 22, 2016 at 7:30
  • Only incomprehensible because I'm a little tired right now, and just being super lazy :D Commented Jul 22, 2016 at 7:46

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.