Skip to content

Instantly share code, notes, and snippets.

@Lelith
Created February 14, 2020 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lelith/5a5d2250a2ba49db8d40bedb2c638a9d to your computer and use it in GitHub Desktop.
Save Lelith/5a5d2250a2ba49db8d40bedb2c638a9d to your computer and use it in GitHub Desktop.
Call callback in componentDidUpdate
/* src/components/Counter/index.js */
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames/bind';
import './index.css';
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
amount: this.props.amount
}
}
increaseAmount() {
this.setState(prevState => (
{amount: prevState.amount +1})
)
}
decreaseAmount() {
this.setState(prevState => (
{amount: prevState.amount -1})
)
}
componentDidUpdate(prevProps, prevState) {
if(prevState !== this.state) {
this.props.callBack(this.state.amount);
}
}
render() {
const {
amount,
callBack,
...other
} = this.props;
const counterClasses = classNames(
'counter',
);
return (
<div className={counterClasses} {...other}>
<button aria-label='decrease' onClick={() => this.decreaseAmount()}>
-
</button>
<input type='text' readOnly value={this.state.amount} aria-label="current amount"/>
<button aria-label='increase' onClick={() => this.increaseAmount()}>
+
</button>
</div>
);
}
}
Counter.propTypes = {
amount: PropTypes.number,
callBack: PropTypes.func.isRequired
};
Counter.defaultProps = {
amount: 0
};
export default Counter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment