I'm trying to write a bit of state which checks if the value in localStorage is a string, if it's null, it should return empty, however the value is a string it should be parsed.
I understand that JSON.parse requires a string, and so I'm not sure what I'm missing when it comes to this narrowing function.
// const [theme, setTheme] = useState(JSON.parse(localStorage.getItem('theme')) || '');
const [theme, setTheme] = useState(() => {
if (localStorage.getItem('theme') !== null) {
return JSON.parse(localStorage.getItem('theme'))
}
else {
return '';
}
}
);
I also tried this...
if (typeof localStorage.getItem('theme') === 'string') {
return JSON.parse(localStorage.getItem('theme'))
}
The error I'm getting is this:
Argument of type 'string | null' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'.ts(2345)
Thanks for your help π