-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
extract access code handling to hook
- Loading branch information
Showing
3 changed files
with
45 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './useAccessCodes.ts' |
32 changes: 32 additions & 0 deletions
32
packages/sdk/packages/access-gate/src/hooks/useAccessCodes.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { useMemo, useState } from 'react' | ||
|
||
export const useAccessCodes = (localStorageKey: string) => { | ||
const [validated, setValidated] = useState(false) | ||
const [codeInput, setCodeInput] = useState('') | ||
|
||
const onAccessCodeSuccess = () => { | ||
// Save the access code to local storage | ||
if (codeInput) { | ||
localStorage.setItem(localStorageKey, JSON.stringify([codeInput])) | ||
setValidated(true) | ||
} else { | ||
// If the codeInput is empty, but we have success, do nothing since the successful code is already saved | ||
setValidated(true) | ||
} | ||
} | ||
const onCodeInputChange = (code?: string) => { | ||
setCodeInput(code ?? '') | ||
return code?.length === 6 | ||
} | ||
const userAccessCodes = useMemo(() => { | ||
const storedCodes = localStorage.getItem(localStorageKey) | ||
if (storedCodes) { | ||
const parsedResult = JSON.parse(storedCodes ?? '') | ||
if (Array.isArray(parsedResult)) return parsedResult | ||
} | ||
}, []) | ||
|
||
return { | ||
validated, userAccessCodes, onAccessCodeSuccess, onCodeInputChange, | ||
} | ||
} |