Search code examples
javascriptapielasticsearchreactjsflux

reactjs displaced events for elasticsearch


I connected an ElasticSearch Route to my ReactJS Service CodeService.js. So that the API get's called on each hit of a key in the input field. That works quite well. When I log each stage of this I can see in the Network and Console that the new objects are treated well.

Instead of on the Order.jsx. There I am always one keystroke behind. When I hit e.g. 0 than I can clearly see that the API is called and it went to the CodeStore.js but calling this.getCodeState().options in Order.jsx prompts with: [] until I hit the 2nd key than I get my previous Store version and not the actual one.

My assumption is that my view becomes rendered before the Store gets updated. How can I target this behaviour?

This is my code:

  export default class Order extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      inputValue: '',
      options: []
    };
    this.props = {
      inputValue: '',
      options: []
    };
    this._onChange = this._onChange.bind(this);
  }

  handleHint(){
    return 'blahblahblha';
  }

  handleComplete(){
    alert('complete!');
  }

  _onChange(event) {
    var enteredChars = event.target.value;
    this.setState({inputValue: enteredChars});
    CodeService.nextCode(enteredChars);
  }

  getCodeState() {
    return {
      options: CodeStore.postcode
    };
  }

  render() {
    return (
      <div className="newer">[...])}

Solution

  • I was able to fix it by adding componentDidMount and added and eventchangelistener.

    componentDidMount() {
      CodeStore.addChangeListener(this._onChange);
    }
    

    The only thing to consider is that you need a condition in your _onChangeevent otherwise you have an infinty loop