2.0.2 • Published 4 years ago

use-state-api-hooks v2.0.2

Weekly downloads
272
License
MIT
Repository
github
Last release
4 years ago

use-state-api-hooks

React hooks for managing and creating reusable stateful object patterns.

NPM JavaScript Style Guide Build Status

Demo

Edit use-state-api-hooks

Install

npm install --save use-state-api-hooks
or 
yarn add use-state-api-hooks

Idea

You can read about the inspiration behind this library here

State API Hooks

useBooleanStateApi

State API for boolean values (T or F states)

Example

import React from "react";
import { useBooleanStateApi } from "use-state-api-hooks";

const BooleanExample = () => {
  const lightSwitch = useBooleanStateApi(false);

  return (
    <div>
      <button onClick={lightSwitch.setTrue} >
        Turn on
      </button>
      <button onClick={lightSwitch.setFalse} >
        Turn off
      </button>
      <button onClick={lightSwitch.toggle} >
        Toggle
      </button>

      <div>The light switch is turned {lightSwitch.state ? "on" : "off"}</div>
    </div>
  );
};

export default BooleanExample;
NameTypeDefaultDescription
stateBooleanState of the boolean object
setStateFunction(state: Boolean): voidSets the boolean state
setTrueFunction(): voidSets state to true
setFalseFunction(): voidSets state to false
toggleFunction(): voidToggles boolean state

useArrayStateApi

State API for arrays (array states)

import React from "react";
import { useArrayStateApi } from "use-state-api-hooks";

const mockData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const ArrayExample = () => {
  const list = useArrayStateApi<number>(mockData);

  return (
    <div>
      <button onClick={list.clear} >
        Clear
      </button>
      <button
        onClick={() => list.push(list.state.length + 1)}
      >
        Push
      </button>
      <button onClick={list.pop} >
        Pop
      </button>
      <button onClick={list.reverse} >
        Reverse
      </button>

      {list.state.map(listItem => (
        <div key={listItem}>{listItem} </div>
      ))}
    </div>
  );
};

export default ArrayExample;
NameTypeDefaultDescription
stateArrayState of the array object
setStateFunction(state: Array): voidSets the array state
clearFunction(): voidEmpty's the array ([])
reverseFunction(): voidReverses the array
popFunction(): voidPops value off of the end of the array (does nothing on empty array)
pushFunction(...vals: T[])Pushes values onto end of the array
shiftFunction(): voidRemoves value from beginning of array (does nothing on empty array)
unshiftFunction(...vals: T[])Pushes values onto beginning of array
insertAtFunction(val: T, index: number): voidInserts value at a given index (Does nothing out of bounds)
upsertAtFunction(val: T, index: number): voidRemoves value from beginning of array (Does nothing out of bounds)
deleteAtFunction(index: number): voidRemoves value from beginning of array (Does nothing out of bounds)

useUniqueArrayStateApi

State API for unique arrays (sets)

NameTypeDefaultDescription
stateArrayState of the array object with unique vals
setStateFunction(state: Array): voidSets the array state with unique vals
clearFunction(): voidEmpty's the array ([])
reverseFunction(): voidReverses the array
toggleFunction(...vals: T[]): voidFor each val, either adds it to the array if it doesn't exist, or removes it if it already exists
popFunction(): voidPops value off of the end of the array (does nothing on empty array)
pushFunction(...vals: T[])Pushes unique values onto end of the array
shiftFunction(): voidRemoves value from beginning of array (does nothing on empty array)
unshiftFunction(...vals: T[])Pushes unique values onto beginning of array
insertAtFunction(val: T, index: number): voidInserts unique value at a given index (Does nothing out of bounds or for nonunique vals)
upsertAtFunction(val: T, index: number): voidRemoves value from beginning of array (Does nothing out of bounds or for nonunique vals)
deleteAtFunction(index: number): voidRemoves value from beginning of array (Does nothing out of bounds)

useCounterStateApi

State API for counters

import React from "react";
import { useCounterStateApi } from "use-state-api-hooks";

const CounterExample = () => {
  const counter = useCounterStateApi({ min: 0, max: 10, count: 0 });

  return (
    <div>
      <button onClick={counter.increment} >
        Increment
      </Button>
      <button onClick={counter.decrement} >
        Decrement
      </Button>

      <h4>
        Count: {counter.count}
      </h4>
    </div>
  );
};
NameTypeDefaultDescription
countNumberValue of the counter
minNumberMinimum possible value of the counter
maxNumberMaximum possible value of the counter
setCountFunction(count: Number): voidSets the counter count
setMinFunction(min: Number): voidSets the counter min
setMaxFunction(max: Number): voidSets the counter max
incrementFunction(): voidIncrement the count by 1 (won't go above max)
incrementByFunction(x: Number): voidIncrement the count by 'x' (won't go above max)
decrementFunction(): voidDecrement the count by 1 (won't go below min)
incrementByFunction(x: Number): voidDecrement the count by 'x' (won't go below min)

useAnchorElStateApi

State API for anchor elements (ie a button that opens a menu in its location)

import React from "react";
import { useAnchorElStateApi } from "use-state-api-hooks";
import Button from "@material-ui/core/Button";
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";

const AnchorElExample = () => {
  const { anchorEl, setAnchorEl, clearAnchorEl } = useAnchorElStateApi(null);

  return (
    <div >
      <Button onClick={setAnchorEl}>Open Menu</Button>
      <Menu
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={clearAnchorEl}
      >
        <MenuItem onClick={clearAnchorEl}>Profile</MenuItem>
        <MenuItem onClick={clearAnchorEl}>My account</MenuItem>
        <MenuItem onClick={clearAnchorEl}>Logout</MenuItem>
      </Menu>
    </div>
  );
};
NameTypeDefaultDescription
anchorElReact.MouseEvent or nullAnchored element
setAnchorElFunction(element: React.MouseEvent or null): voidSets the anchored element
clearAnchorElFunction(): voidClears the anchored element (sets anchorEl state to null)
setStateFunction(state: {count: Number, min: Number, max: Number}): voidSets the counter state

Creating your own StateAPIs

In addition to providing some common stateful object patterns, useStateApiHooks can be used to build your own stateful api's. This library follows compositional factory patterns, where each stateful api has a state api factory describing the state api interface. The useStateApi hook is a general hook at the base of every state api hook that takes a state api factory as a first argument, and an initial state as a second argument.

useStateApi(<yourStateApiFactory>, <initialState>);

From there, it memoizes the state and state methods, and returns your state api hook.

useStateApi example

Below is an example of how you would use useStateApi to create a boolean stateful object using JS. If you are using TS, here is the source code.

// this is how to create useBooleanStateApi is created using JS
import { useStateApi } from 'use-state-api-hooks';

export const booleanStateApiFactory = (setState) => ({
  setTrue: () => setState(true),
  setFalse: () => setState(false),
  toggle: () => setState(!state)
});

export const useBooleanStateApi = (initialState) => useStateApi(booleanStateApiFactory, initialState);

useStateApi compositional architecture

For scalable architecture, useStateApiHooks suggests using compositional factory patterns. This will help prevent architectural problems associated with classical inheritance, and will give you decoupled reusable factory methods.

// mammalMethods.js
const play = (state) => {...}
const walk = (state) => {...}
const run = (state) => {...}


// useCatStateApi.js
import { useStateApi } from 'use-state-api-hooks';
import { play, walk, run } from './mammalMethods';

export const catStateApiFactory = ({ state, setState }) => {
  return {

    // these are methods imported from mammalMethods.
    // setState will pass the state into each function
    play: () => setState(play),
    walk: () => setState(walk),
    run: () => setState(run),

    // these are specific cat methods
    meow: () => {...}
    takeBath: () => {...}
  };
};

export const useCatStateApi = (initialState) => useStateApi(dogStateApiFactory, initialState);

// useDogStateApi.js
import { useStateApi } from 'use-state-api-hooks';
import { play, walk, run } from './mammalMethods';

export const dogStateApiFactory = ({ state, setState }) => ({

  // these are methods imported from mammalMethods
  // setState will pass the state into each function
  play: () => setState(play(state)),
  walk: () => setState(walk(state)),
  run: () => setState(run(state)),

  // these are specific dog methods
  bark: () => {...}
  wagTail: () => {...}
});

export const useDogStateApi = (initialState) => useStateApi(dogStateApiFactory, initialState);

License

MIT © BenBrewerBowman


This hook is created using create-react-hook.

2.0.2

4 years ago

2.0.1

4 years ago

2.0.0

4 years ago

1.5.0

4 years ago

1.4.0

4 years ago

1.3.1

4 years ago

1.3.0

4 years ago

1.2.2

5 years ago

1.2.1

5 years ago

1.1.0

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago