Skip to content

Commit

Permalink
doc: write documnentation for useSession (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
alamenai committed Jun 13, 2024
1 parent 5aa05aa commit 6587407
Show file tree
Hide file tree
Showing 3 changed files with 211 additions and 4 deletions.
1 change: 1 addition & 0 deletions pages/hooks/_meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"use-local-storage": "useLocalStorage",
"use-persistent-state": "usePersistentState",
"use-query-params": "useQueryParams",
"use-session": "useSession",
"use-timeout": "useTimeout",
"use-unsaved-form-changes": "useUnsavedFormChanges",
"use-url": "useUrl"
Expand Down
206 changes: 206 additions & 0 deletions pages/hooks/use-session.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import AvatarCircles from "@/components/magic-ui/avatar.circles.tsx";

# useSession

<h3 className="mt-4 text-xl font-normal text-gray-400">A custom hook for managing session storage.</h3>

## Usage

```tsx {3,7,8,9,10,11,12,13,14,15,16,17} copy

import React from 'react';
import { useSession } from './useSession';

function App() {
const {
session,
getValue,
getMultipleValues,
addItem,
addMultipleItems,
renameKey,
deleteItem,
deleteItemAfterDelay,
deleteMultipleItems,
clearSessionStorage,
} = useSession();

return (
<div>
<h1>useSession Example</h1>
<button onClick={() => addItem('key1', 'value1')}>Add Item</button>
<button onClick={() => deleteItem('key1')}>Delete Item</button>
<button onClick={() => clearSessionStorage()}>Clear Session Storage</button>
<p>Session Data: {JSON.stringify(session)}</p>
</div>
);
}

export default App;


```

## Hook

```ts copy
import { useEffect, useState } from 'react'

export type Item = string | number | object | null

export const useSession = (fn?: () => void) => {
const items = getCurrentSession()

const [session, setSession] = useState<{ [x: string]: Item }[]>(items)

useEffect(() => {
if (fn && typeof fn == 'function') {
fn()
}
}, [session, fn])

const getValue = (itemKey: string) => {
const items = Object.values(session)

for (const item of items) {
if (itemKey in item) {
return item[itemKey]
}
}

return null
}

const renameKey = (oldKey: string, newKey: string) => {
const item = checkItem(oldKey)

if (!item) {
throw new Error('This item does not exist in the session storage')
}

const value = sessionStorage.getItem(oldKey)

sessionStorage.removeItem(oldKey)

if (value) {
sessionStorage.setItem(newKey, value)
setSession(getCurrentSession())
}
}

const getMultipleValues = (keys: string[]) => {
const multipleValues: string[] = []

keys.forEach(key => {
const value = getValue(key) as string
multipleValues.push(value)
})

return multipleValues
}

const addItem = (key: string, value: Item) => {
if (typeof value === 'object') {
sessionStorage.setItem(key, JSON.stringify(value))
}

if (typeof value === 'number') {
sessionStorage.setItem(key, value.toString())
}

if (typeof value === 'string') {
sessionStorage.setItem(key, value)
}

setSession([...session, { [key]: value }])
}

const addMultipleItems = (items: { key: string; value: string }[]) => {
for (const item of items) {
addItem(item.key, item.value)
}
}

const deleteItem = (key: string) => {
const item = checkItem(key)
if (!item) {
throw new Error('This item does not exist in the session storage')
}

if (item) {
sessionStorage.removeItem(key)
setSession(getCurrentSession())
}
}

const deleteItemAfterDelay = (key: string, time: number) => {
setTimeout(() => {
deleteItem(key)
}, time)
}

const deleteMultipleItems = (keys: string[]) => {
keys.forEach(key => {
deleteItem(key)
})
}

const clearsessionStorage = () => {
sessionStorage.clear()
setSession([])
}

return {
session,
getValue,
getMultipleValues,
addItem,
addMultipleItems,
renameKey,
deleteItem,
deleteItemAfterDelay,
deleteMultipleItems,
clearsessionStorage,
}
}

export const checkItem = (key: string) => sessionStorage.getItem(key)

export const getCurrentSession = () => {
const items: { [x: string]: string | null }[] = []

const keys = Object.keys(sessionStorage)

keys.forEach(key => {
items.push({ [key]: sessionStorage.getItem(key) })
})

return items
}


```

## API

<h1 className='text-xl font-medium mt-6'>Parameters</h1>

| Parameter | Type | Description |
| --------- | ---- | ----------- |
| `fn` | `() => void` (optional) | A function to run on session state change. |

<h1 className='text-xl font-medium mt-6'>Returs</h1>

| Name | Type | Description |
| --------------------- | ---------------------------------- | ------------------------------------------------ |
| `session` | `{ [x: string]: Item }[]` | The current session state. |
| `getValue` | `(itemKey: string) => Item` | Retrieves the value of a specific item. |
| `getMultipleValues` | `(keys: string[]) => string[]` | Retrieves the values of multiple items. |
| `addItem` | `(key: string, value: Item) => void` | Adds an item to the session storage. |
| `addMultipleItems` | `(items: { key: string; value: string }[]) => void` | Adds multiple items to the session storage. |
| `renameKey` | `(oldKey: string, newKey: string) => void` | Renames a key in the session storage. |
| `deleteItem` | `(key: string) => void` | Deletes an item from the session storage. |
| `deleteItemAfterDelay`| `(key: string, time: number) => void` | Deletes an item after a delay. |
| `deleteMultipleItems` | `(keys: string[]) => void` | Deletes multiple items from the session storage. |
| `clearSessionStorage` | `() => void` | Clears all items from the session storage. |

8 changes: 4 additions & 4 deletions theme.config.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,18 @@ const config = {

project: {
link: "https://github.com/alamenai/rehook",

},

chat: {
link: 'https://x.com/AlaMenai',
link: "https://x.com/AlaMenai",
icon: (
<svg width="24" height="24" viewBox="0 0 248 204">
<path
fill="currentColor"
d="M221.95 51.29c.15 2.17.15 4.34.15 6.53 0 66.73-50.8 143.69-143.69 143.69v-.04c-27.44.04-54.31-7.82-77.41-22.64 3.99.48 8 .72 12.02.73 22.74.02 44.83-7.61 62.72-21.66-21.61-.41-40.56-14.5-47.18-35.07a50.338 50.338 0 0 0 22.8-.87C27.8 117.2 10.85 96.5 10.85 72.46v-.64a50.18 50.18 0 0 0 22.92 6.32C11.58 63.31 4.74 33.79 18.14 10.71a143.333 143.333 0 0 0 104.08 52.76 50.532 50.532 0 0 1 14.61-48.25c20.34-19.12 52.33-18.14 71.45 2.19 11.31-2.23 22.15-6.38 32.07-12.26a50.69 50.69 0 0 1-22.2 27.93c10.01-1.18 19.79-3.86 29-7.95a102.594 102.594 0 0 1-25.2 26.16z"
/>
</svg>
)
),
},

sidebar: {
Expand All @@ -77,7 +76,8 @@ const config = {
title === "useEnv" ||
title === "useMouse" ||
title === "useUnsavedFormChanges" ||
title === "useCookie") && (
title === "useCookie" ||
title === "useSession") && (
<Badge className=" absolute -right-[0.5em] bg-transparent border-lime-400 text-lime-500 px-[0.5em] hover:bg-transparent">
New
</Badge>
Expand Down

0 comments on commit 6587407

Please sign in to comment.