Here I'm fetching an API inside a React Component to display cat facts. I'm using setInterval function to fetch the data in every five seconds after the initial render.
But I noticed that in every five seconds my UI get rendering twice( I can see two cat facts at a time, first one get vanished instantly). Also, I checked that few times my UI getting re-rendered before the five seconds interval. Can anyone explain me this?
import { Component } from "react";
class App extends Component {
state = { cats: " " };
getCats() {
fetch("https://catfact.ninja/fact")
.then((response) => response.json())
.then((data) => this.setState({ cats: data.fact }));
}
componentDidMount() {
setInterval(() => this.getCats(), 5000);
}
render() {
return <h3>{this.state.cats}</h3>;
}
}
export default App;