2

I met a problem when I use semantic-ui-react(version: 0.78.3). I was trying to use onSearchChange function in Dropdown. I changed states with this.setState in onSearchChange function.

But when I input the first alphabet, the query state doesn't change at all(still empty). When I input the second alphabet, the query state will change into the first alphabet.

Here is the code:

class SearchBookForm extends Component {
  state = {
    query: '',
    loading: false,
    options: [{
      key: 1,
      value: 1,
      text: 'first book'
    }]
  }

  onSearchChange = (e, data) => {
    
    // log four different variables before this.setState
    console.log(data.searchQuery)
    console.log(this)
    console.log(this.state.query)
    console.log(this.state.loading);
    
    this.setState({ query: data.searchQuery, loading: !this.state.loading });

    // log one variable after this.setState
    console.log(this.state.query)
  }

  render(){
    return (
      <Form>
        <Dropdown
          search
          fluid
          placeholder="Search for a book by title"
          onSearchChange={this.onSearchChange}
          options={this.state.options}
          loading={this.state.loading}
        />
      </Form>
    )
  }
};

To make it more clear, I log four variables in onSearchChange function, when I type "p" in the form, the log result is as follows: Log result 1

data.searchQuery changes into p. In this, its state(query and loading) has been changed, although this.setState is at the end of the function. But the third and fifth variables this.state.query are nothing and the fourth variable this.state.loading doesn't change as well.

When I type the second alphabet "l", this.state.query changes into "p", and this.state.loading changes as well. It seems setState works, but always falls behind. The result pic is here: Log result 2

I hope my explanation makes sense. I am so confused. Is it a bug in semantic-ui-react? What is the logic in onSearchChange function?

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
  • let me know if you have any doubt? – Mayank Shukla Mar 08 '18 at 17:47
  • Before setState, why the state changes when log "this", but not "this.state.query"? – Hongkuan Wang Mar 08 '18 at 18:25
  • when you are printing the this, there will be any `i` icon near to object, hover over that icon and see what it prints. value of array/object will be evaluated when you expand the object/array in console so it will always print the updated/latest value but when you print any value it will print the value at that moment not the updated one, hope you will get the idea :) – Mayank Shukla Mar 08 '18 at 19:17

0 Answers0