Skip to content

Commit

Permalink
Merge pull request #1 from laxmanpokhrel/dev
Browse files Browse the repository at this point in the history
dev
  • Loading branch information
laxmanpokhrel authored Oct 26, 2023
2 parents 9d06bb0 + a9cf428 commit 9a94f1f
Show file tree
Hide file tree
Showing 6 changed files with 174 additions and 65 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: Release
on:
push:
branches:
- release # branch in which you want the publish to happen
- main # branch in which you want the publish to happen

permissions:
contents: read # for checkout
Expand Down
1 change: 0 additions & 1 deletion index.ts

This file was deleted.

18 changes: 11 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"name": "@xmanscript/utils",
"name": "@xmanscript/uselocalstorage",
"version": "1.0.0-semantically-released",
"description": "Complex utility functions package with 20+ utility functions.",
"description": " custom hook that simplifies local storage management in your React applications.",
"repository": {
"type": "git",
"url": "https://github.com/**.git"
"url": "https://github.com/laxmanpokhrel/xmanscript-use-local-storage"
},
"keywords": [
"utils",
Expand All @@ -14,9 +14,9 @@
"light weight"
],
"bugs": {
"url": "https://github.com/**/issues"
"url": "https://github.com/laxmanpokhrel/xmanscript-use-local-storage/issues"
},
"homepage": "https://github.com/**#readme",
"homepage": "https://github.com/laxmanpokhrel/xmanscript-use-local-storage#readme",
"main": "./lib/index.js",
"scripts": {
"build": "rm -rf lib && tsc",
Expand Down Expand Up @@ -51,11 +51,11 @@
"lint-staged": "^14.0.1",
"nodemon": "^3.0.1",
"prettier": "^3.0.3",
"semantic-release": "^22.0.0",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.6",
"semantic-release": "^22.0.0"
"typescript": "^5.1.6"
},
"peerDependencies": {
"react": "*"
Expand All @@ -73,5 +73,9 @@
},
"publishConfig": {
"access": "public"
},
"dependencies": {
"@types/react": "^18.2.32",
"react": "^18.2.0"
}
}
142 changes: 88 additions & 54 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,85 +1,119 @@
# @xmanscript/uselocalstorage

[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
## Introduction

# NPM Package Template
`@xmanscript/uselocalstorage` is a React custom hook that simplifies local storage management in your React applications. It provides a convenient way to read and write data to the browser's local storage and handle changes to local storage values. This hook is designed to be versatile and easy to use.

Use this template to quickly set up and release npm packages with ease. This template is configured to automate the release process using semantic-release and provides commitizen support for standardized commit messages.
## Table of Contents

## Getting Started
1. [Installation](#installation)
2. [Basic Usage](#basic-usage)
3. [API](#api)
4. [Examples](#examples)

To get started with this template, follow these steps:
## Installation

1. Click the "Use this template" button at the top of the repository to create a new repository based on this template.
You can install `@xmanscript/uselocalstorage` using npm or yarn:

2. Clone the newly created repository to your local machine:
```bash
npm install @xmanscript/uselocalstorage
# or
yarn add @xmanscript/uselocalstorage
```
## Basic Usage
To use the useLocalStorage hook, import it in your React component and call it with a key that corresponds to your local storage item. Optionally, you can provide a callback function to handle changes to the local storage value.

Here's a simple example:
```tsx
import React from 'react';
import useLocalStorage from '@xmanscript/uselocalstorage';

function MyComponent() {
const { getItem, setItem, removeItem } = useLocalStorage('myKey', () => {
// This callback will be triggered when 'myKey' changes in other tabs or windows.
// You can update your component's state or take other actions here.
});

// Use the functions to interact with local storage
const storedValue = getItem(); // Retrieve the value
setItem('newData'); // Set a new value
removeItem(); // Remove the item from local storage
}
```

```bash
git clone https://github.com/your-username/your-package.git
```
## API
### useLocalStorage(key: string, onStorageChange?: () => any)

3. Change into the project directory:
* `key` (string, required): The key used to identify the local storage item.
* `onStorageChange` (function, optional): A callback function that is triggered when the local storage item with the specified key changes in other tabs or windows.

```bash
cd your-package
```
Returns an object with the following methods:

4. Install the project dependencies:
* `getItem(): string | null`: Retrieves the value stored in local storage.
* `setItem(value: string)`: void: Sets a new value in local storage and triggers the onStorageChange callback (if provided).
* `removeItem(): void`: Removes the item from local storage and triggers the onStorageChange callback (if provided).

```bash
yarn install
```

### Initializing Husky
## Examples
### Creating an Authentication Hook
Here's an example of creating an authentication hook using useLocalStorage:
```tsx
import { useState } from 'react';
import useLocalStorage from '@xmanscript/uselocalstorage';

Husky is a tool that helps you set up Git hooks easily. These hooks can run checks or tasks before you commit or push changes. This template uses Husky to enforce commit message conventions.
export default function useAuth() {
// Create a React state variable to keep track of the authentication status.
const [isAuthenticated, setIsAuthenticated] = useState(!!localStorage.getItem('token'));

To initialize Husky, run the following command:
// Use the useLocalStorage hook to manage the 'token' key in local storage.
const { setItem, removeItem } = useLocalStorage('token', () => {
// This callback is triggered when the 'token' value in local storage changes.
// It allows you to update the component's state based on changes to the 'token'.
const newToken = localStorage.getItem('token');
setIsAuthenticated(!!newToken);
});

```bash
npx husky-init && yarn
// The logIn function is used to set the 'token' in local storage.
function logIn(authToken: string) {
setItem(authToken); // Set the 'token' to the provided value.
}

// The logOut function is used to remove the 'token' from local storage.
function logOut() {
removeItem(); // Remove the 'token' from local storage.
}

// Return an object with authentication status and functions to log in and out.
return { isAuthenticated, logIn, logOut };
}
```
Explanation:

### Initializing Commitizen
1. The useAuth hook is designed to manage authentication in your application. It keeps track of the user's authentication status using a 'token' stored in local storage.

Commitizen is a tool that helps you write consistent and conventional commit messages. It prompts you to fill in the required commit message fields, ensuring your commits are well-structured.
2. The useState hook is used to create a state variable called isAuthenticated. It's initialized based on the presence of a 'token' in local storage. If a 'token' exists, isAuthenticated is set to true; otherwise, it's false.

To initialize Commitizen with this template, run the following command:
3. The useLocalStorage hook is used to manage the 'token' key in local storage. It takes a callback function as an argument, which is executed whenever the 'token' value in local storage changes. In this example, the callback function updates the isAuthenticated state variable based on the presence of the 'token.'

```bash
npx commitizen init cz-conventional-changelog --yarn --dev --exact --force
```
- **Github Actions branch change:** You have to modify the
banch name to the branch name in which you want the release job to start.
4. The logIn function allows users to log in by setting the 'token' in local storage. It takes an authToken parameter, which is the token returned after a successful login. The setItem function from useLocalStorage is used to set this value in local storage.

```
name: Release
on:
push:
branches:
- <<release brnach name>>
```
5. The logOut function is used to log the user out. It removes the 'token' from local storage using the removeItem function from useLocalStorage.

- **Custom TypeScript Configuration**: You can modify the TypeScript configuration in `tsconfig.json` to suit your project's needs.
Finally, the useAuth hook returns an object with the current authentication status (isAuthenticated) and functions to log in (logIn) and log out (logOut).

## Contributing

We welcome contributions to this project. If you have any bug fixes, feature additions, or improvements, please open an issue or submit a pull request. Make sure to follow the commit message conventions for your pull requests.

## License
## Conclusion

This project is licensed under the MIT License.
## Acknowledgments
The `@xmanscript/uselocalstorage` custom hook simplifies local storage management and provides a flexible way to handle changes in local storage values. It offers a convenient API to interact with local storage, making it easy to create applications that require client-side data persistence.

- [Semantic Release](https://semantic-release.gitbook.io/semantic-release/)
- [Commitizen](http://commitizen.github.io/cz-cli/)
- [Husky](https://typicode.github.io/husky/)
- [ESLint](https://eslint.org/)
- [Prettier](https://prettier.io/)
- [Jest](https://jestjs.io/)
- [TypeScript](https://www.typescriptlang.org/)
Key benefits of using `@xmanscript/uselocalstorage`:

## Support
- Effortless local storage management: Store and retrieve data in local storage with ease.
- Real-time updates: The hook triggers callbacks when local storage values change in other tabs or windows.
- Versatility: Use it for various use cases, from authentication tokens to user preferences.
- Improved user experience: Keep your application's state in sync with local storage changes.

If you have any questions or need assistance, please feel free to reach out through the GitHub Issues section of this repository.
We encourage you to explore the capabilities of `@xmanscript/uselocalstorage` and consider how it can enhance your React applications. Whether you're building a user authentication system, saving user preferences, or managing application state, this hook is a valuable addition to your toolkit.

Happy coding! 🚀
Feel free to reach out to us for support or to report any issues on [GitHub](https://github.com/laxmanpokhrel/xmanscript-use-local-storage/issues). We look forward to seeing how you use `@xmanscript/uselocalstorage` to streamline your development process and improve the user experience of your applications.
43 changes: 42 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,42 @@
export {};
import * as React from 'react';

export default function useLocalStorage(key: string, onChange?: () => any) {
function setItem(value: string) {
try {
localStorage.setItem(key, value);
} catch (error) {
throw new Error('Error setting the value to local storage.');
}
}

function getItem(): string | null {
try {
return localStorage.getItem(key);
} catch (error: any) {
return null;
}
}

function removeItem() {
try {
localStorage.removeItem(key);
} catch (error) {
throw new Error('Error removing the item from local storage.');
}
}

React.useEffect(() => {
const handleStorageChange = () => {
if (onChange) {
onChange();
}
};
window.addEventListener('storage', handleStorageChange);

return () => {
window.removeEventListener('storage', handleStorageChange);
};
}, [key, onChange]);

return { setItem, getItem, removeItem };
}
33 changes: 32 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1260,6 +1260,25 @@
resolved "https://registry.yarnpkg.com/@types/normalize-package-data/-/normalize-package-data-2.4.1.tgz#d3357479a0fdfdd5907fe67e17e0a85c906e1301"
integrity sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw==

"@types/prop-types@*":
version "15.7.9"
resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.9.tgz#b6f785caa7ea1fe4414d9df42ee0ab67f23d8a6d"
integrity sha512-n1yyPsugYNSmHgxDFjicaI2+gCNjsBck8UX9kuofAKlc0h1bL+20oSF72KeNaW2DUlesbEVCFgyV2dPGTiY42g==

"@types/react@^18.2.32":
version "18.2.32"
resolved "https://registry.yarnpkg.com/@types/react/-/react-18.2.32.tgz#7ec787730c45ee9a3c0ed150b19e95c31fe4608a"
integrity sha512-F0FVIZQ1x5Gxy/VYJb7XcWvCcHR28Sjwt1dXLspdIatfPq1MVACfnBDwKe6ANLxQ64riIJooXClpUR6oxTiepg==
dependencies:
"@types/prop-types" "*"
"@types/scheduler" "*"
csstype "^3.0.2"

"@types/scheduler@*":
version "0.16.5"
resolved "https://registry.yarnpkg.com/@types/scheduler/-/scheduler-0.16.5.tgz#4751153abbf8d6199babb345a52e1eb4167d64af"
integrity sha512-s/FPdYRmZR8SjLWGMCuax7r3qCWQw9QKHzXVukAuuIJkXkDRwp+Pu5LMIVFi0Fxbav35WURicYr8u1QsoybnQw==

"@types/semver@^7.5.0":
version "7.5.2"
resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.5.2.tgz#31f6eec1ed7ec23f4f05608d3a2d381df041f564"
Expand Down Expand Up @@ -2381,6 +2400,11 @@ cssesc@^3.0.0:
resolved "https://registry.yarnpkg.com/cssesc/-/cssesc-3.0.0.tgz#37741919903b868565e1c09ea747445cd18983ee"
integrity sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==

csstype@^3.0.2:
version "3.1.2"
resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.1.2.tgz#1d4bf9d572f11c14031f0436e1c10bc1f571f50b"
integrity sha512-I7K1Uu0MBPzaFKg4nI5Q7Vs2t+3gWWW648spaF+Rg7pI9ds18Ugn+lvg4SHczUdKlHI5LWBXyqfS8+DufyBsgQ==

cz-conventional-changelog@3.3.0, cz-conventional-changelog@^3.3.0:
version "3.3.0"
resolved "https://registry.yarnpkg.com/cz-conventional-changelog/-/cz-conventional-changelog-3.3.0.tgz#9246947c90404149b3fe2cf7ee91acad3b7d22d2"
Expand Down Expand Up @@ -5084,7 +5108,7 @@ longest@^2.0.1:
resolved "https://registry.yarnpkg.com/longest/-/longest-2.0.1.tgz#781e183296aa94f6d4d916dc335d0d17aefa23f8"
integrity sha512-Ajzxb8CM6WAnFjgiloPsI3bF+WCxcvhdIG3KNA2KN962+tdBsHcuQ4k4qX/EcS/2CRkcc0iAkR956Nib6aXU/Q==

loose-envify@^1.4.0:
loose-envify@^1.1.0, loose-envify@^1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf"
integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==
Expand Down Expand Up @@ -6192,6 +6216,13 @@ react-is@^18.0.0:
resolved "https://registry.yarnpkg.com/react-is/-/react-is-18.2.0.tgz#199431eeaaa2e09f86427efbb4f1473edb47609b"
integrity sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==

react@^18.2.0:
version "18.2.0"
resolved "https://registry.yarnpkg.com/react/-/react-18.2.0.tgz#555bd98592883255fa00de14f1151a917b5d77d5"
integrity sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==
dependencies:
loose-envify "^1.1.0"

read-cmd-shim@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/read-cmd-shim/-/read-cmd-shim-4.0.0.tgz#640a08b473a49043e394ae0c7a34dd822c73b9bb"
Expand Down

0 comments on commit 9a94f1f

Please sign in to comment.