capacitor-community / capacitor-community/react-hooks

Bug: Storage API always returns string on web

Open
#4 4 comments 5 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
267
Forks
24
PR merge metrics
No merged PRs in 30d

Description

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

```js
const [ myObj , setMyObj ] = useStorageItem('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:

```diff
- 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`.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.