Last active
October 28, 2022 16:02
-
-
Save iivanovw7/808419b7fd7b5e323d5ca74584b7ddc7 to your computer and use it in GitHub Desktop.
useMap.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
import { | |
Dispatch, | |
SetStateAction, | |
useCallback, | |
useMemo, | |
useState, | |
} from "react"; | |
export type TMapOrEntries<Key, Value> = Map<Key, Value> | [Key, Value][]; | |
export type TUseMapActions<Key, Value> = { | |
setValue: Dispatch<SetStateAction<Map<Key, Value>>>; | |
delete: (keyToRemove: Key) => void; | |
set: (key: Key, value: Value) => void; | |
clear: Map<Key, Value>["clear"]; | |
initialize: (pairsOrMap: TMapOrEntries<Key, Value>) => void; | |
}; | |
export type TUseMap<Key, Value> = [Map<Key, Value>, TUseMapActions<Key, Value>]; | |
export const useMap = <Key, Value>( | |
initialState: TMapOrEntries<Key, Value> = new Map(), | |
): TUseMap<Key, Value> => { | |
const [map, setMap] = useState( | |
Array.isArray(initialState) ? new Map(initialState) : initialState, | |
); | |
const set = useCallback((key: Key, value: Value) => { | |
setMap((aMap) => { | |
const copy = new Map(aMap); | |
return copy.set(key, value); | |
}); | |
}, []); | |
const deleteByKey = useCallback((key: Key) => { | |
setMap((_map) => { | |
const copy = new Map(_map); | |
copy.delete(key); | |
return copy; | |
}); | |
}, []); | |
const clear = useCallback(() => { | |
setMap(() => new Map()); | |
}, []); | |
const initialize = useCallback( | |
(mapOrTuple: TMapOrEntries<Key, Value> = []) => { | |
setMap(() => new Map(mapOrTuple)); | |
}, | |
[], | |
); | |
const actions = useMemo( | |
() => ({ | |
setValue: setMap, | |
clear, | |
set, | |
delete: deleteByKey, | |
initialize, | |
}), | |
[clear, deleteByKey, initialize, set], | |
); | |
return [map, actions]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment