Skip to content

[BUG]: @toss/react default values setting of useStorageState  #421

@okinawaa

Description

@okinawaa

Package Scope

Package name: @toss/react

Describe the bug

If a value is initialized through defaultValue, the value is not set in the session storage.

Expected behavior

Even if the set function is not executed, if the value is initialized through defaultValue, the value must be set in the session storage.

To Reproduce

const [state, set] = useStorageState('dummy-key', { defaultValue: 'foo'}); // it doesn't stored in session storage until we call set funciton

Possible Solution

const getValue = useCallback(<T>() => {
    const data = storage.get(key);

    if (data == null) {
      return defaultValue;
    }

    try {
      const result = JSON.parse(data);

      if (result == null) {
        storage.set(key, JSON.stringify(defaultValue)); // add this line
        return defaultValue;
      }

      return result as T;
    } catch {
      // NOTE: JSON 객체가 아닌 경우
      return defaultValue;
    }
  }, [defaultValue, key, storage]);

Additional context

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