@gramypomagamy/react-replicant-store
v1.0.0
Published
A simple Zustand-based NodeCG replicant store for use with React applications.
Downloads
3
Readme
@gramypomagamy/react-replicant-store
An external Replicant store and hooks for that store for React-based NodeCG bundles. Powered by Zustand.
Usage
To create a store you need to create a type for your Replicant map in this format:
type ReplicantMap = {
bundle1: {
replicant1: Replicant1Type;
replicant2: Replicant2Type;
},
bundle2: {
replicant3: Replicant3Type;
replicant4: Replicant4Type;
}
}This is to get proper autocomplete and typing of Replicant values.
Example:
import { createReplicantStore } from '@gramypomagamy/react-replicant-store';
type ReplicantMap = {
"my-bundle": {
counter: { value: number };
timer: { remaining: number };
};
};
const replicantStore = createReplicantStore<ReplicantMap>();Hooks
This package allows you to export hooks for easy access to the Replicants by passing your created store and it's type.
Example:
import { createReplicantStore, createReplicantHooks } from '@gramypomagamy/react-replicant-store';
type ReplicantMap = {
"my-bundle": {
counter: { value: number };
timer: { remaining: number };
};
};
const replicantStore = createReplicantStore<ReplicantMap>();
const { useReplicant, useReplicantValue } = createReplicantHooks<ReplicantMap>(replicantStore);The available hooks are:
useReplicant- a hook returning a tuple of both a value and a function to update the value
const [replicant, setReplicant] = useReplicant('my-bundle', 'replicant');useReplicantValue- a hook that returns a read-only value
const replicant = useReplicantValue('my-bundle', 'replicant');If you want to be closer to NodeCG's Replicant API, you can define a helper function with a default namespace name like this:
const replicantStore = createReplicantStore<ReplicantStore>();
const hooks = createReplicantHooks<ReplicantStore>(replicantStore);
export function useReplicant<N extends keyof ReplicantStore>(
name: Extract<keyof ReplicantStore[N], string>,
namespace: N = 'my-bundle' as N
) {
const [replicant, setReplicant] = hooks.useReplicant(namespace, name);
return [replicant, setReplicant];
}
export function useReplicantValue<N extends keyof ReplicantStore>(
name: Extract<keyof ReplicantStore[N], string>,
namespace: N = 'my-bundle' as N
) {
return hooks.useReplicantValue(namespace, name);
}