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:

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
}) 

Leave a Reply