0

I am converting class components into functional components and get the error during removing 'this'.

The original project (with class components) runs well. But when I remove 'this' from 'this.intervalID', it shows an error

It confuses me, because 'intervalID' is declared nowhere in the project (neither state, props), only appears in the code below (in the functions startInterval() and stopInterval).

Maybe I have not yet understood fully how 'this' is used in a class component. Can anyone help? And maybe also help me: how to convert these kind of 'this' in conversion to a functional component.

 startInterval = () => {
 this.intervalID = setInterval(this.updateData, 15000);
};
stopInterval = () => {
 clearInterval(this.intervalID);
};

Thank you very much!

asked Jan 23, 2022 at 14:50

1 Answer 1

2

You should not use 'this' in functional components. If you need the intervalID you can save it in a new state.

MyComponent = () => {
 const [intervalID, setIntervalID] = useState()
 
 const updateData = () => {...}
 startInterval = () => {
 const interval = setInterval(updateData, 15000)
 setIntervalID(interval)
 }
 
 stopInterval = () => {
 clearInterval(intervalID)
 }
}
answered Jan 23, 2022 at 15:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.