-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implemented hook for validated state (#261)
- Loading branch information
1 parent
a6baae4
commit e963214
Showing
2 changed files
with
72 additions
and
60 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,41 @@ | ||
import React from "react"; | ||
|
||
export function useValidState<T, K = any>( | ||
initialState: T | (() => T), | ||
validStates: readonly T[] | [readonly K[], (element: K) => T], | ||
keepStateWhenInvalid = true | ||
): [T, (newState: T | ((prevState: T) => T), acceptInvalidState?: boolean) => void] { | ||
const [state, setState] = React.useState<T>(initialState); | ||
|
||
let validState = state; | ||
const computedInitialState = typeof initialState === "function" ? (initialState as () => T)() : initialState; | ||
|
||
let adjustedValidStates: T[] = []; | ||
if (validStates.length === 2 && Array.isArray(validStates[0]) && typeof validStates[1] === "function") { | ||
adjustedValidStates = validStates[0].map(validStates[1] as (element: K) => T); | ||
} else { | ||
adjustedValidStates = validStates as T[]; | ||
} | ||
|
||
if (!adjustedValidStates.includes(state)) { | ||
if (adjustedValidStates.length > 0) { | ||
validState = adjustedValidStates[0]; | ||
} else { | ||
validState = computedInitialState; | ||
} | ||
if (!keepStateWhenInvalid) { | ||
setState(validState); | ||
} | ||
} | ||
|
||
function setValidState(newState: T | ((prevState: T) => T), acceptInvalidState = true) { | ||
const computedNewState = typeof newState === "function" ? (newState as (prevState: T) => T)(state) : newState; | ||
if (!acceptInvalidState && !adjustedValidStates.includes(computedNewState)) { | ||
return; | ||
} | ||
|
||
setState(newState); | ||
} | ||
|
||
return [validState, setValidState]; | ||
} |