Skip to content

Revisiting Hooks implementation #32

Open
@krizzu

Description

@krizzu

You want to:

Discuss required changes to current 'hook-ish' implementation for Hooks support.

Details:

As you can see here, we've got a nice wrapper on top AsyncStorage, to mimic hooks usage.
This discussion here is to come up with better and valid implementation, that leverages hooks API.

Example implementation could look like this:

function useAsyncStorage(key, defaultValue) {
  const [storageValue, updateStorageValue] = useState(defaultValue);

  useEffect(() => {
    getStorageValue();
  }, []);

  async function getStorageValue() {
    let value = defaultValue;
    try {
      value = (await AsyncStorage.getItem(key)) || defaultValue;
    } catch (e) {
      // handle here
    } finally {
      updateStorageValue(value);
    }
  }

  async function updateStorage(newValue) {
    try {
      await AsyncStorage.setItem(key, newValue);
    } catch (e) {
      // handle here
    } finally {
      getStorageValue();
    }
  }

  return [storageValue, updateStorage];
}

The problem in here is that, once we got a value inside AsyncStorage, we'll be getting two rerenders one component mounting - one returning the default value, second the actual stored data.

I'm more than happy to discuss this, so please let me know what you think.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions