I can’t getItem from localStorage the error is "Argument of type ‘string | null’ is not assignable to parameter of type ‘string’.
Type ‘null’ is not assignable to type ‘string’.ts(2345)
var localStorage: Storage" and "Argument of type ‘string | null’ is not assignable to parameter of type ‘string’.
Type ‘null’ is not assignable to type ‘string’."
const getLocalStorage = () => {
let groceryList = localStorage.getItem('grocery-list');
if (groceryList) {
return (groceryList = JSON.parse(localStorage.getItem('grocery-list')));`here is the error here is the error in localStorage and 'grocery-list'`
} else {
return [];
}
};
function App() {
const [list, setList] = useState(getLocalStorage());
useEffect(() => {
localStorage.setItem('grocery-list', JSON.stringify(list));
}, [list]);`here I set item to localStorage`
}
2
Answers
localstorage.getItem returns a string or undefined. By adding your if check, you guard against that. However because you call JSON.parse on another call to localstorage instead of the variable you defined the guard does no longer work. Instead do this
The
JSON.parse
method requires its first argument to be of typestring
, notnull
.The problematic code is
JSON.parse(localStorage.getItem('grocery-list'))
.The type of
localStorage.getItem('grocery-list')
could bestring
ornull
and thus you get the error.I’d refactor your
getLocalStorage
function code to:Note the
if
statement: we first check thegroceryList
is not null and this is why inside we can work withstring
type.