0.0.5 • Published 2 years ago

cross-local-storage v0.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

GitHub branch checks state GitHub Workflow Status codecov

Stargazers

Issues

MIT License

LinkedIn

Bootstrapped with https://www.npmjs.com/package/react-component-lib-boilerplate

·

Report Bug

·

Request Feature

About The Project

This library was built while I was working on a project based on react-native-web, where the goal was to maximize the code sharing between the web and native codebase.
Many pieces of shared business logic (thunks, sagas or whatever) at some time needed to persist something (eg: save token after login).
This library creates an unique interface that can be used to interact with the localStorage regardless that that your app is running in a browser or with react-native. Moreover, thanks to typescript augmentation, cross-local-storage expose an augmentable interface to allow you to define the keys of your local storage so it will be much easier to remember the keys used to read and write data

Getting Started

Install the library from npm registry

Installation

This is an example of how to list things you need to use the software and how to install them.

  • npm

npm i apperside/cross-local-storage
  • yarn

yarn add apperside/cross-local-storage
REACT NATIVE USERS

If you use this library on the web, you are good to go. If you are running on react-native instead, you need to install '@react-native-community/async-storage', here you can find the full docs

Usage

This library is basically a cross-platform implementation of the following interface

export interface ILocalStorage {
	setItem: (key: keyof LocalStorageKeys, data?: string | null) => void | Promise<any>;
	getItem: (key: keyof LocalStorageKeys) => Promise<string | null>;
	removeItem: (key: keyof LocalStorageKeys) => Promise<boolean>;
	setBoolean: (
		key: keyof LocalStorageKeys,
		data?: boolean | null,
	) => Promise<boolean | void>;
	getBoolean: (key: keyof LocalStorageKeys) => Promise<boolean>;
	setJson: (
		key: keyof LocalStorageKeys,
		data: any,
	) => Promise<boolean | void>;
	getJson: <T = any>(key: keyof LocalStorageKeys) => Promise<T | null>;
	setNumber: (
		key: keyof LocalStorageKeys,
		data: number,
	) => Promise<boolean | void>;
	getNumber: (key: keyof LocalStorageKeys, defaultValue?: number | null) => Promise<number | null>;
	multiSet: (data: LocalStorageKeyValuePair) => Promise<boolean>;
	multiGet: (
		...keys: (keyof LocalStorageKeys)[]
	) => Promise<LocalStorageKeyValuePair>;
	multiRemove: (...keys: (keyof LocalStorageKeys)[]) => Promise<boolean>;
	clear: () => void;
	enableLogging: (enabled: boolean) => void;
}

LocalStorageKeys is a type alias which represents the keys of the enum LocalStorageKeysEnum , which you can augment to provide the allowed keys for read and write operations (you can find more about typescript's declaration merging feature in the dedicated documentation).

Here is how it is defined

export enum LocalStorageKeysEnum {
	// TO BE AUGMENTED
}

export type LocalStorageKeys = keyof  typeof LocalStorageKeysEnum;

This is an example of how you can extend the enum

/**
* You have to add this declaration wherever you want to augment librariy's types
*/

declare  module  "cross-local-storage" {
	/**
	* Augment this interface to add al custom endpoints
	*/

	export enum LocalStorageKeysEnum {
		myLocalStorageKey,
		anotherLocalStorageKey
	}
}

After you augment the interface, you can use the library very easily

// since it is the default export, you can rename crossLocalStorage with whatever you want
import crossLocalStorage from "cross-local-storage"

// with async/await
const value = await crossLocalStorage.getItem("myLocalStorageKey")

// with promises
crossLocalStorage.getItem("myLocalStorageKey")
.then(value=>{
	alert("result is "+value);
})

await crollLocalStorage.setItem("myLocalStorageKey" , "my value");

// returns a key-value pair
await crollLocalStorage.multiGet("myLocalStorageKey" , "my value");

IMPORTANT Since react-native's AsyncStorage api are async, you need an async approach on web too.

FULL API

methoddescription
setItemit takes in input one of the keys [you have defined](#key-declarations) and the value you want to set. The value can be anything, it will be stringified. If you pass null or undefined, the value will be removed
getItemit takes in input one of the keys [you have defined](#key-declarations) and returns the value or null if it does not exist
removeItemit takes in input one of the keys [you have defined](#key-declarations) and removes that value. It returns a boolean indicating if the operation succeeded or not.
setBooleanutility method to save a boolean value. It takes in input one of the keys [you have defined](#key-declarations) and the value you want to set. The value must be a boolean otherwise you get a typescript error (if you are using it). If you pass a string different from "true", it will fail (don't save anything). If you pass null or undefined false will be set
getBooleanutility method to retrieve a boolean value. It takes in input one of the keys [you have defined](#key-declarations) and returns the value as a boolean
setNumberutility method to save a number value. It takes in input one of the keys [you have defined](#key-declarations) and the value you want to set. The value must be a valid number otherwise an exception will be thrown. You can also pass null or undefined to remove that key
getNumberutility method to retrieve a number value. It takes in input one of the keys [you have defined](#key-declarations) and an optional default value to return in case the key is not found (returns null by default)
setJsonutility method to save a stringified json value. It takes in input one of the keys [you have defined](#key-declarations) and the value you want to set. The value can be anything, it will be saved as JSON.stringify(value)
getJsonutility method to retrieve a parsed json value. It takes in input one of the keys [you have defined](#key-declarations) and returns the value parsed with JSON.parse(value). If you are using typescript, you can pass the generic parameter to infer return type
multiSetaccepts a key-value pair (where the keys must be one of the keys [you have defined](#key-declarations)) to save multiple items at the same time
multiGetaccepts an arbitrary number of keys that [you have defined](#key-declarations) and returns a key-value pair with the respective values
multiRemoveaccepts an arbitrary number of keys that [you have defined](#key-declarations) and removes multiple items at the same time
clearremove everything from local storage
enableLogginga function to set the logger active or not. By default it is active if process.env.NODE_ENV == 'development' || process.env.NODE_ENV == 'dev'. If it is active, it will log all operations you perform with local storage

Roadmap

  • Publish initial version

[] Add Continuous Integration [] Add typed bindings between storage keys and the type of value it stores

See the [open issues](https://github.com/apperside/cross-local-storage/issues) for a full list of proposed features (and known issues).

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".

Don't forget to give the project a star! Thanks again!

  1. Fork the Project

  1. Create your Feature Branch (git checkout -b feature/AmazingFeature)

  1. Commit your Changes (git commit -m 'Add some AmazingFeature')

  1. Push to the Branch (git push origin feature/AmazingFeature)

  1. Open a Pull Request

License

Distributed under the MIT License. See LICENSE.txt for more information.

Contact

Apperside - https://apperside.com - info@apperside.com

Project Link: [https://github.com/apperside/cross-local-storage](https://github.com/apperside/cross-local-storage)