Ashraful
Ashraful

Reputation: 1964

setState is not working inside event function

I have declared on constructor,

this.onProjectSelect.bind(this);

Ths is outside render and outside of constructor,

onProjectSelect(event) {
    this.setState({project: event.target.value});
    event.preventDefault();
}

JSX View

<Select2
data={BasicStore.projectsSelect2Format}
onChange={this.onProjectSelect}
options={{
    placeholder: 'Search Project',
}}
/>

I don't understand my mistakes here. Please help me to to get out of here. Thanks

Upvotes: 0

Views: 2714

Answers (2)

Tomas Ramirez Sarduy
Tomas Ramirez Sarduy

Reputation: 17471

I think you could be missing the state initializing on the constructor, or maybe you are just making a mistake in the binding. I would do something like this:

export default class Test extends Component{

  constructor(props) {
    super(props)

    this.state = {
      project: ''
    }
  }

  onProjectSelect = (e) => {
    this.setState({
      project: e.target.value
    });
  }

  render(){
    return (
      <Select2
        data={BasicStore.projectsSelect2Format}
        onChange={this.onProjectSelect}
        options={{
          placeholder: 'Search Project',
        }}
      />
    )
  }
}

Upvotes: 2

DocMax
DocMax

Reputation: 12164

Are you just calling this.onProjectSelect.bind(this); or are you assigning it back go this.onProjectSelect? The bind function returns a new function, so I would expect to see:

this.onProjectSelect = this.onProjectSelect.bind(this);

Upvotes: 3

Related Questions