skip to Main Content

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


  1. 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

    
    const getLocalStorage = () => {
      let groceryList = localStorage.getItem('grocery-list');
      if (groceryList) {
        return JSON.parse(groceryList);
      } else {
        return [];
      }
    };
    
    
    Login or Signup to reply.
  2. The JSON.parse method requires its first argument to be of type string, not null.

    The problematic code is JSON.parse(localStorage.getItem('grocery-list')).
    The type of localStorage.getItem('grocery-list') could be string or null and thus you get the error.

    I’d refactor your getLocalStorage function code to:

    const getLocalStorage = () => {
      const groceryList = localStorage.getItem('grocery-list');
    
      if (groceryList) {
        return JSON.parse(groceryList);
      }
    
      return [];
    };
    
    

    Note the if statement: we first check the groceryList is not null and this is why inside we can work with string type.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search