При вызове метода fetchData через clearInterval появляется ошибка и все исчезает, смотрел вроде бы проблема в каких-то рекурсивных вызовах, как от этого избавиться непонятно Ошибка: Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
export class CryptoCurrency extends React.Component<CryptoCurrencyProps, CryptoCurrencyState>{
constructor(props: CryptoCurrencyProps) {
super(props);
this.state = {usd: null, error: '', status: CryptoEnum.NONE, intervalId: null};
this.remove = this.remove.bind(this);
}
componentDidMount() {
this.fetchData();
let intervalObj = setInterval(() => this.fetchData(), 5000);
this.setState({intervalId: intervalObj})
}
fetchData() {
fetch(`https://min-api.cryptocompare.com/data/price?fsym=${this.props.cryptoName}&tsyms=USD&api_key=${API_KEY}`)
.then(res => res.json())
.then(
(result) => {
this.setState({
usd: result.USD
});
},
(error) => {
this.setState({
error: error
});
}
)
}
remove() {
this.props.removeCurrency(this.props.cryptoName);
}
componentDidUpdate(prevProps: CryptoCurrencyProps, prevState: CryptoCurrencyState) {
if (prevState.usd && this.state.usd != null) {
if (prevState.usd > this.state.usd) {
this.setState({ status: CryptoEnum.DOWN });
} else if (prevState.usd < this.state.usd) {
this.setState({ status: CryptoEnum.UP });
} else {
this.setState({ status: CryptoEnum.EQUAL });
}
}
}
componentWillUnmount(){
if (this.state.intervalId){
clearInterval(this.state.intervalId);
}
}
render(): any {
return <div>
{this.props.cryptoName}{this.state.usd} {this.state.status} <button onClick={this.remove}>Удалить</button>
</div>
}
}