I would like to make sure that a function is called exactly one time, depending on some props and state.
class MyComponent extends Component {
state = {
externalInfoPresent: false,
infoSaved: false,
}
async componentDidMount() {
await this.props.refreshExternalInfo();
this.setState({ externalInfoPresent: true });
if (this.props.externalInfo !== undefined && !this.state.infoSaved) {
await this.saveMyInfo();
}
}
async componentDidUpdate(prevProps) {
if (prevProps.externalInfo === this.props.externalInfo || this.state.infoSaved) return;
await this.saveMyInfo();
}
async saveMyInfo() {
if (this.props.externalInfo === undefined || this.state.infoSaved) return;
// logic for saving stuff to external service
this.setState({ infoSaved });
}
// render and other stuff
}
saveMyInfo() depends on externalInfo being present.
I would like saveMyInfo() to only be called once but it's being called twice with my current logic.