Home > Mobile >  useState and localStorage: argument of type 'string null' is not assignable to parameter o
useState and localStorage: argument of type 'string null' is not assignable to parameter o

Time:12-15

I'm using NextJS, and i am trying to make a state persist using localStorage, i did it like this:

const [reportFavorite, setReportFavorite] = useState([
    'captura',
    'software',
    'upload',
  ] as any)

  useEffect(() => {
    setReportFavorite(JSON.parse(window.localStorage.getItem('reportFavorite')))
  }, [])

  useEffect(() => {
    window.localStorage.setItem('reportFavorite', reportFavorite)
  }, [reportFavorite])

But TypeScript returns this error: argument of type 'string | null' is not assignable to parameter of type 'string'

I read some answers on StackOverflow telling me that if i did:

useEffect(() => {
    setReportFavorite(JSON.parse(window.localStorage.getItem('reportFavorite')!))
  }, [])

Using the !, it would fix it, but it didn't, if i do that i get another error saying invalid character on line.

CodePudding user response:

Try this:

const [reportFavorite, setReportFavorite] = useState([
    'captura',
    'software',
    'upload',
  ] as any)

  useEffect(() => {
    const reportFavouriteInStorage = localStorage.getItem('reportFavorite');
    if(!!reportFavouriteInStorage){
      setReportFavorite(JSON.parse(reportFavouriteInStorage))
    }
  }, [])

  useEffect(() => {
    localStorage.setItem('reportFavorite', reportFavorite)
  }, [reportFavorite])
  • Related