By not going into the actual usage, I have created a simple example to explain what I want to do.
I have a state object {num:0}
and I want to update the num after every second for 10 seconds and according to that, I created a class component that is working perfectly fine.
class App extends React.Component {
constructor() {
super();
this.state = {
num: 0
};
}
componentDidMount = () => {
for (let i = 0; i < 10; i++) {
setTimeout(() => this.setState({ num: this.state.num + 1 }), i * 1000);
}
};
render() {
return (
<>
<p>hello</p>
<p>{this.state.num}</p>
</>
);
}
}
Now I want to replicate the same functionality in the functional component but I am unable to. I tried as shown below:
const App = () => {
const [state, setState] = React.useState({ num: 0 });
React.useEffect(() => {
for (let i = 0; i < 10; i++) {
setTimeout(() => setState({ num: state.num + 1 }), i * 1000);
}
}, []);
return (
<>
<p>hello</p>
<p>{state.num}</p>
</>
);
};
Can anyone please help me with what I am doing wrong here?