Why the fetch image button onClick function works in function expression, but not function declaration in the same calling method.
class FetchButtom extends Component {
async fectchImage() {
const IMAGE_API = 'Some Image API';
try {
const images = await fetch(IMAGE_API);
const json = await images.json();
console.log(this);
this.props.addImage(json.items);
} catch (error) { }
}
fectchImageExpression = async () => {
const IMAGE_API = 'Some Image API';
try {
const images = await fetch(IMAGE_API);
const json = await images.json();
console.log(this);
this.props.addImage(json.items);
} catch (error) { }
}
render() {
return (
<div>
<button
// console.log(this); -> this point to FetchButtom
onClick={() => this.fectchImage()}
// This will no trigger fectchImage runs
onClick={() => this.fectchImage}
// TypeError: Cannot read property 'props' of undefined
onClick={this.fectchImage}
// Working perfectly, same as onClick={() => this.fectchImage()}
onClick={() => this.fectchImageExpression()}
// This will no trigger fectchImageExpression runs
onClick={() => this.fectchImageExpression}
// Working perfectly, same as onClick={() => this.fectchImage()}
onClick={this.fectchImageExpression}
>
Fetch image
</button>
</div>
);
}
}
So, my question is why function expression have these 2 cases working {() => this.fectchImageExpression()} and {this.fectchImageExpression}, function declaration only working in {() => this.fectchImage()}
()you are invoking the function