React 18 bindings for key-value-state-container
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.
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 });
};
}, []);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;useSelectorwill not refresh a React component forstatusattribute change, if used this way:
const { body, engine, status } = useSelector<Car, Action>({
containerId,
statePath: ["body", "engine"],
});as statePath is not including status attribute.
- remove all
node_modulesfolders manually - make necessary changes to
key-value-state-containerand bump the version temporarily up (e.g.1.0.5->1.0.6) - run
npm run packinkey-value-state-containerto create a tgz package locally in~folder - change
package.jsoninkey-value-state-container-reactto 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)