Search code examples
javascriptreact-nativereadonly

react-native state is read-only


Following Component in react-native:

import { useEffect, useState } from 'react'

let startValue = null // only using this to restart the counter from resetTimer() (other better approaches?)

export const NewTimer = () => {
  const [seconds, setSeconds] = useState(startValue)

  const formatedTime = () => {
    return [pad(parseInt(seconds / 60)), pad(seconds % 60)].join(':')
  }

  useEffect(() => {
    const timer = setInterval(() => setSeconds(++seconds), 1000) // I guess this line triggers the error
    return () => {
      clearInterval(timer)
    }
  }, [])

  return formatedTime
}

const pad = (num) => {
  return num.toString().length > 1 ? num : `0${num}`
}

export const resetTimer = () => {
  startValue = 0
}

results in Uncaught Error: "seconds" is read-only

Can anyone point where the mistake is? Thx!


Solution

  • when you do ++seconds, you are attempting to mutate seconds this render, which isn't allowed. I would use the setState callback to get the current value, and just do seconds + 1, which will accomplish the same thing:

    useEffect(() => {
      const timer = setInterval(() => setSeconds((seconds) => seconds + 1), 1000)
      return () => {
        clearInterval(timer)
      }
    }, [])