@lesnoypudge/utils-react
Version:
lesnoypudge's utils-react
39 lines (38 loc) • 1.13 kB
JavaScript
import { useFunction } from "../useFunction/useFunction.js";
import { useLatest } from "../useLatest/useLatest.js";
import { useState } from "react";
const useMap = (defaultValue) => {
const [value, setValue] = useState(() => new Map(defaultValue));
const valueRef = useLatest(value);
const _set = useFunction((...args) => {
const newValue = new Map(valueRef.current);
Map.prototype.set.apply(newValue, args);
setValue(newValue);
return newValue;
});
const _delete = useFunction((...args) => {
const newValue = new Map(valueRef.current);
const res = Map.prototype.delete.apply(newValue, args);
setValue(newValue);
return res;
});
const _clear = useFunction(() => {
setValue(/* @__PURE__ */ new Map());
});
return {
clear: _clear,
delete: _delete,
entries: value.entries.bind(value),
forEach: value.forEach.bind(value),
get: value.get.bind(value),
has: value.has.bind(value),
keys: value.keys.bind(value),
set: _set,
size: value.size,
values: value.values.bind(value)
};
};
export {
useMap
};
//# sourceMappingURL=useMap.js.map