useMap

Custom hook that manages a key-value Map state with setter actions.

Usage

import { Fragment } from "react";
import { useMap } from "@teasim/hooks";
export default function Component() {
const [map, actions] = useMap([["key", "๐Ÿ†•"]]);
const set = () => {
actions.set(String(Date.now()), "๐Ÿ“ฆ");
};
const setAll = () => {
actions.setAll([
["hello", "๐Ÿ‘‹"],
["data", "๐Ÿ“ฆ"],
]);
};
const reset = () => {
actions.reset();
};
const remove = () => {
actions.remove("hello");
};
return (
<div>
<button onClick={set}>Add</button>
<button onClick={reset}>Reset</button>
<button onClick={setAll}>Set new data</button>
<button onClick={remove} disabled={!map.get("hello")}>
{'Remove "hello"'}
</button>
<pre>
Map (
{Array.from(map.entries()).map(([key, value]) => (
<Fragment key={key}>{`\n ${key}: ${value}`}</Fragment>
))}
<br />)
</pre>
</div>
);
}