I am running a function that downloads the data from the server and runs it after an interval with the help of setInterval. The issue is that I am unable to change the state of the component inside the setInterval(inside the function I have defined). I need this state to be changed because Child component needs to re-render a few things whenever downloads happen.
Here is the similar code (just for demo purpose) which demonstrate the problem I am facing.
import React, { useState, useEffect, useRef, useReducer } from 'react';
import './App.css';
import Child from './Child';
const App = () => {
const [reset, setReset] = useState(false);
const changeState = () => {
console.log('changing state from', reset);
setReset(!reset);
console.log('changing state to', reset);
};
const init = () => {
setInterval(changeState, 1000);
};
return (
<>
<button onClick={init}>Start</button>
<button onClick={changeState}>Change</button>
<Child reset={reset} />
</>
);
};
export default App;
Change button state of the button changes perfectly.start button (click it once), it will start calling the setReset to change the state but it has no impact. This is how the output looks like in this case.Child component
import React, { useState, useEffect, useRef, useReducer } from 'react';
const Child = (props) => {
return (
<>
{props.reset ? "hello" : "tello"}
</>
);
};
export default Child;
You can edit the code here https://stackblitz.com/edit/react-aj5wdf?devtoolsheight=33&file=src/App.js
Note: I have beginner-level experience with React.
Thanks.