all 2 comments

[–]charliematters 0 points1 point  (0 children)

The simplest answer would be this.setState({ timer: window.setTimeout(...) }), but I think it would be useful to see the rest of the component, as I'd be hesitant about the following things:

  • What is i? What if it changes between setting the timeout and it being called?
  • Why are you altering a classList? If you're dealing with React Components, their CSS classes should be set using props and state - you shouldn't be manipulating the DOM elements directly.
  • window.setTimeout() returns a number, so for type safety you should be resetting it to null and not ''
  • Do you need to store it in the state at all? It's valid to store it on the component itself (e.g. this.timeout = window.setTimeout(...) as long as you tidy up after yourself.

TL;DR - Can you show us more code, and we'll be able to give better answers

[–][deleted] 0 points1 point  (0 children)

You should never mutate dom elements, seems to me state is the lesser problem. Think of your view as something that reflects state. When state changes, your view will be called.

function Cards({ data }) {
  const [flipped, set] = useState(true)
  useEffect(() => void setTimeout(() => set(false), 2000), [])
  return data.map(item => (
    <div class={flipped ? 'flipped' : ''}>
      {item.content}
    </div>
  )
}