I am trying to call a function (with values of title and category) when a button is clicked. The values are stored in the state of the component, and the values are correct when I console.log(this.state). However, when the function is called, the value of title remains but category becomes undefined.
It works when I put the function that I want to call into another function, I'm not sure why the original binding caused one of the values to become undefined. Was "this" lost, and where was it lost at?
I have tried understanding the explanations in React this.state is undefined? , https://javascript.info/bind , Binding this? Getting undefined? and Are 'Arrow Functions' and 'Functions' equivalent / exchangeable? but I don't think it explains the behaviour experienced in mine.
Was I using too much this/bind which caused the problem?
class CreateItem extends React.Component {
constructor(props) {
super(props);
this.state = {
inputTitle: '',
selectedCategory: ''
}
}
// works when I put the createItem(title, category) inside this function
onClickAddItem() {
this.props.createItem(this.state.inputTitle, this.state.selectedCategory);
}
render() {
<div>
// this doesn't work (edit: due to typo where it should be selectedCategory and not inputCategory)
<Button text={'Create'} onClick={this.props.createItem.bind(this, this.state.inputTitle, this.state.inputCategory)}/>
// this works
<Button text={'Create'} onClick={this.onClickAddItem.bind(this)}/>
</div>
}
}
// createPublicChat function is in another file
export function createItem(title, category) {
console.log(title, category);
}
I expected the output of title = "BookA", category = "Fiction" to print "Book A Fiction" to console, but the actual output is "Book A undefined"
Edit: There was a typo which caused the undefined issue (as pointed out by @bkm412). Both works now, thank you!