useMapState

About

A react hook to manage state in a key value pair map.

Examples

import "./styles.css";
import { useMapState } from "rooks";
import { useState } from "react";

export default function App() {
  const [
    map,
    { set, setMultiple, has, remove, removeMultiple, removeAll },
  ] = useMapState({ a: 1, b: 2 });
  const [setInputKey, setSetInputKey] = useState("");
  const [setInputValue, setSetInputValue] = useState("");
  const [removeInputKey, setRemoveInputKey] = useState("");

  return (
    <div className="App">
      <h1>useMapState CodeSandbox</h1>

      <div className="input">
        <input
          value={setInputKey}
          onChange={e => setSetInputKey(e.target.value)}
          placeholder="key"
        />
        <input
          value={setInputValue}
          onChange={e => setSetInputValue(e.target.value)}
          placeholder="value"
        />
        <button onClick={() => set(setInputKey, setInputValue)}>set</button>
      </div>

      <div className="input">
        <input
          value={removeInputKey}
          onChange={e => setRemoveInputKey(e.target.value)}
          placeholder="key"
        />
        <button onClick={() => remove(removeInputKey)}>remove</button>
      </div>

      {Object.entries(map).map(item => {
        return <div>{item.join(": ")}</div>;
      })}
    </div>
  );
}

Arguments

Argument valueTypeDescriptionDefualt
initialValueObjectInitial value of the mapundefined

Returns

Returns an array of following items:

Return valueTypeDescription
mapanyvalue of the map
methodsObjectmethods to modify the map, see the table below

map methods:

Return valueTypeDescription
set(key: any, value: any) => voidset a key value pair in map
has(key: any) => booleanif key exists in map
setMultiple(...keys: any[]) => voidset multiple key value pair in map
remove(key: any) => voidremove a key value pair in map
removeMultiple(...keys: any[]) => voidremove multiple key value pair in map
removeAll() => voidremove all key value pair in map

Join the community!

Join our discord server! You can click the floating discord icon at the bottom right of the screen and chat with us!

Powered by vercel