Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React state with boolean type in local storage in typescript

So I have a react state that tracks dark/light mode by darkMode being false or true.

const [darkMode, setDarkMode] = useState(false)

And I have a function that changes the state:

const handleChange = () => {
    setDarkMode(prevDarkMode => localStorage.setItem('darkMode', JSON.stringify(!prevDarkMode))) 
  }

I get 2 errors:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1.Argument of type ‘(prevDarkMode: boolean) => void’ is not assignable to parameter of type ‘SetStateAction’.

2.Type ‘(prevDarkMode: boolean) => void’ is not assignable to type ‘(prevState: boolean) => boolean’.
Type ‘void’ is not assignable to type ‘boolean’.

How do I fix this?

>Solution :

Need to return a value in setState

setDarkMode(prevDarkMode => {
   localStorage.setItem('darkMode', JSON.stringify(!prevDarkMode))
   return !prevDarkMode
}) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading