sushinpv / react-secure-storage

This is a wrapper written above local storage to write the data securely to local storage
https://npmjs.com/package/react-secure-storage
MIT License
126 stars 12 forks source link

Unable to retrieve the value for the given key when setting VITE_SECURE_LOCAL_STORAGE_PREFIX #50

Open siddhartha8916 opened 2 months ago

siddhartha8916 commented 2 months ago

HI, unable to retrieve a value for the given key when using VITE_SECURE_LOCAL_STORAGE_PREFIX else when using default prefix it woks fine

type AllowedDataTypes = string | boolean | number | object;

export const useSecureLocalStorage = (
  keyName: string,
  defaultValue: string | boolean | number | object
): [AllowedDataTypes, (value: AllowedDataTypes) => void] => {
  const [storedValue, setStoredValue] = useState<AllowedDataTypes>(() => {
    try {
      const value = secureLocalStorage.getItem(keyName);
      if (value) {
        return value;
      } else {
        secureLocalStorage.setItem(keyName, defaultValue);
        return defaultValue;
      }
    } catch (err) {
      return defaultValue;
    }
  });

  const setValue = (newValue: AllowedDataTypes) => {
    try {
      secureLocalStorage.setItem(keyName, newValue);
    } catch (err) {
      console.error("Unable to store value to Local Storage", err);
      throw new Error("Unable to store value to Local Storage");
    }
    setStoredValue(newValue);
  };
  return [storedValue, setValue];
};

Not getting the currentUser value when checking with this

const useUser = () => {
  const [currentUser, setCurrentUser] = useSecureLocalStorage(
    "currentUser",
    ""
  );

  const updateUser = (newUser: object) => {
    setCurrentUser(newUser);
  };

  return {
    user: currentUser as I_AppSurveyUser,
    setUser: updateUser,
  };
};

export default useUser;