diff --git a/src/App.tsx b/src/App.tsx index 0728518c0d8..3849f49567c 100755 --- a/src/App.tsx +++ b/src/App.tsx @@ -8,6 +8,7 @@ import './App.css'; */ interface IState { data: ServerRespond[], + isStreaming: boolean, // Add this to track streaming status } /** @@ -15,13 +16,14 @@ interface IState { * It renders title, button and Graph react element. */ class App extends Component<{}, IState> { + private intervalId: NodeJS.Timeout | null = null; // Store the interval ID + constructor(props: {}) { super(props); this.state = { - // data saves the server responds. - // We use this state to parse data down to the child element (Graph) as element property data: [], + isStreaming: false, // Initialize streaming status }; } @@ -39,10 +41,44 @@ class App extends Component<{}, IState> { DataStreamer.getData((serverResponds: ServerRespond[]) => { // Update the state by creating a new array of data that consists of // Previous data in the state and the new data from server - this.setState({ data: [...this.state.data, ...serverResponds] }); + this.setState(prevState => ({ + data: [...prevState.data, ...serverResponds] + })); }); } + /** + * Start streaming data + */ + startStreaming() { + if (this.state.isStreaming) return; // Prevent starting multiple intervals + + this.setState({ isStreaming: true }); + this.intervalId = setInterval(() => { + this.getDataFromServer(); + }, 100); + } + + /** + * Stop streaming data + */ + stopStreaming() { + if (!this.state.isStreaming) return; + + this.setState({ isStreaming: false }); + if (this.intervalId) { + clearInterval(this.intervalId); + this.intervalId = null; + } + } + + componentWillUnmount() { + // Clean up the interval when the component is unmounted + if (this.intervalId) { + clearInterval(this.intervalId); + } + } + /** * Render the App react component */ @@ -53,15 +89,18 @@ class App extends Component<{}, IState> { Bank & Merge Co Task 2
- +
{this.renderGraph()}