Skip to content

Bug: Storage API always returns string on web #4

Open
@ricoberger

Description

@ricoberger

Hi, the following code always returns a string instead of an object after a page reload:

const [ myObj , setMyObj ] = useStorageItem<object>('myobj');

const set = () => {
  setMyObj({
    'key1': 'value1',
    'key2': 'value2',
  });
};

// After the set function is calledmyObj is of type object, but after a page reload myObj is of type string
console.log(myObj);

I think it's caused by the following line https://github.com/ionic-team/ionic-react-hooks/blob/76745d1b3a0b4c62949dd6095ede3cbb4843c9ab/src/storage/useStorage.ts#L87 because on the web the type of result.value is always string. Which is because of the implementation of the storage API for the web, where localStorage.getItem() always returns a string or null for the value key: https://github.com/ionic-team/capacitor/blob/f08e4a4f3cff1eedca3ca7292da7892ab2de5806/core/src/web/storage.ts#L21

I fixed it for me the following way:

-          setStoredValue(typeof result.value === 'string' ? result.value : JSON.parse(result.value!));
          
+          try {
+            const parsedValue = JSON.parse(result.value!);
+            setStoredValue(parsedValue);
+          } catch (err) {
+            setStoredValue(result.value);
+          }

If you want I can submit a PR with the change, but I think there should be a better solution than using try and catch.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions