react-hooks icon indicating copy to clipboard operation
react-hooks copied to clipboard

Bug: Storage API always returns string on web

Open ricoberger opened this issue 5 years ago • 4 comments

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.

ricoberger avatar Jan 06 '20 19:01 ricoberger

Hi,

I made a fix for this in the the pull request #8

slevy85 avatar May 18 '20 19:05 slevy85

hey, I stumbled upon this bug today. Is there a path forward for merging the PR? Thanks for your time on this project.

jakobhellermann avatar Jul 23 '20 14:07 jakobhellermann

@elylucas Is there any estimate to approve the PR #8 ?

leandrogehlen avatar Aug 27 '20 18:08 leandrogehlen

It's been over a year since a PR was proposed to address this but not a peep from maintainers. Also close to a year since any material changes were made to this repo, can we assume this is unmaintained?

gugahoi avatar Jun 01 '21 01:06 gugahoi