Skip to content

sharpcoding/key-value-state-container-react

Repository files navigation

React 18 bindings for key-value-state-container

How to use

First, register container with either with registerStateContainer or <ContainerRoot /> component. <ContainerRoot /> has all the props exact to registerStateContainer function attributes.

Then dispatchAction or useDispatchAction hook is used to dispatch actions to the container.

Then registerStateChangedCallback or useSelector in your React code to refresh components when some attributes changed.

Advanced use-cases

It is totally perfect to use registerActionDispatchedCallback in component code like this:

import {
  registerActionDispatchedCallback,
  getUniqueId,
} from "key-value-state-container";

useEffect(() => {
  const listenerId = getUniqueId();
  registerActionDispatchedCallback({
    callback: ({ action }) => { },
    listenerId,
    //...
  });
  return () => {
    unregisterActionDispatchedCallback({ listenerId });
  };
}, []);

Common pitfall: not listening to an attribute changes

Let's say there is a state like this:

type Car = {
  engine: {
    horsepower: number;
    cylinders: number;
  };
  body: {
    type: "sedan" | "coupe";
    color: "black" | "red" | "white";
  };
  status: "working" | "broken";
  year: number;
};

type State = Car;
  • useSelector will not refresh a React component for status attribute change, if used this way:
const { body, engine, status } = useSelector<Car, Action>({
  containerId,
  statePath: ["body", "engine"],
});

as statePath is not including status attribute.

How to develop locally with key-value-state-container

  • remove all node_modules folders manually
  • make necessary changes to key-value-state-container and bump the version temporarily up (e.g. 1.0.5 -> 1.0.6)
  • run npm run pack in key-value-state-container to create a tgz package locally in ~ folder
  • change package.json in key-value-state-container-react to use the local tgz package:
    "dependencies": {
      "key-value-state-container": "file:~/key-value-state-container-1.0.0.tgz",
    }
  • don't forget to bump the version back to the original one (e.g. 1.0.6 -> 1.0.3)

About

React 18 bindings for key-value-state-container

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published