Skip to content

Initial commit #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,11 @@ as `statePath` is not including `status` attribute.

- 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` to create a tgz package locally
- 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:
```js
"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`)
15 changes: 9 additions & 6 deletions src/ContainerRoot/ContainerRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,24 +39,26 @@ export const ContainerRoot = <TState extends Object, TAction extends Action>(
) => {
const [autoContainerId] = useState<string>(getUniqueId());
const {
autoActions,
autoState,
children,
config,
containerId = autoContainerId,
dispatcher,
initialState,
reducer,
persistence,
reducer,
} = props;
const runningFirstTimeRef = useRef<boolean>(true);
if (runningFirstTimeRef.current) {
runningFirstTimeRef.current = false;
registerStateContainer({
autoActions,
autoState,
config,
containerId,
dispatcher,
initialState,
reducer,
persistence,
reducer,
});
}

Expand All @@ -68,12 +70,13 @@ export const ContainerRoot = <TState extends Object, TAction extends Action>(
*/
if (reRegister({ containerId })) {
registerStateContainer({
autoActions,
autoState,
config,
containerId,
dispatcher,
initialState,
reducer,
persistence,
reducer,
});
}
return () => {
Expand Down
2 changes: 1 addition & 1 deletion src/use-dispatch-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import { useContext } from "react";
import { Action, dispatchAction } from "key-value-state-container";

import { UseDispatchAction } from "types/contracts";
import { UseDispatchAction } from "./types/contracts";
import {
ContainerRootContext,
ContainerRootContextProps,
Expand Down
64 changes: 54 additions & 10 deletions src/use-selector.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import { useEffect, useRef, useState } from "react";
import {
import {
Action,
ClientNotificationCallbackArgs,
getContainer,
getUniqueId,
registerStateChangedCallback,
TKnownStatePath,
unregisterStateChangedCallback,
getUniqueId,
} from "key-value-state-container";
import { useGetContainerId } from "./use-get-container-id";
import { RendersWithContainerId } from "./types/contracts";

interface Args<TState extends Object> extends Partial<RendersWithContainerId> {
interface Args<TState extends Object, TAction extends Action = Action>
extends Partial<RendersWithContainerId> {
callback?: (args: ClientNotificationCallbackArgs<TState, TAction>) => void;
/**
* Diagnostics flag that helps to identify problems
* @default true
Expand All @@ -25,15 +28,40 @@ interface Args<TState extends Object> extends Partial<RendersWithContainerId> {
*/
lateInvoke?: boolean;
listenerTag?: string;
statePath: TKnownStatePath<TState>[];

statePath: TKnownStatePath<TState>[] | TKnownStatePath<TState>;

/**
* When `true`, selector code will be not active (will not register any callback)
* and always return the current container state (as it is), so the hook will no
* longer be a hook, but a simple function.
*
* Reason for introduction: it is not possible to have code that calls hooks
* conditionally, as this will violate rules of hooks, so this is a workaround.
* So, in other words, it is not possible to have something like this:
*
* ```
* if (hookNonNecessary) {
* return;
* }
* const result = useHook();
* ```
* The purpose is to makes code more linear and easier to maintain.
*/
switchOff?: boolean;
}

export const useSelector = <TState extends Object, TAction extends Action>({
export const useSelector = <
TState extends Object,
TAction extends Action = Action
>({
callback,
containerId: containerIdFromProps,
ignoreUnregistered,
lateInvoke,
lateInvoke: lateInvokeFromProps,
listenerTag,
statePath,
switchOff,
}: Args<TState>) => {
const listenerIdRef = useRef<string>(
`${listenerTag ? `${listenerTag}:` : ""}${getUniqueId()}`
Expand All @@ -47,22 +75,31 @@ export const useSelector = <TState extends Object, TAction extends Action>({
ignoreUnregistered:
typeof ignoreUnregistered === "boolean" ? ignoreUnregistered : true,
}) || {};
const lateInvoke =
typeof lateInvokeFromProps === "boolean" ? lateInvokeFromProps : true;
const [currentState, setCurrentState] = useState(initialState);
useEffect(() => {
return () => {
unmountedRef.current = true;
};
}, []);
useEffect(() => {
if (switchOff) {
return;
}
const statePaths =
typeof statePath === "string"
? [statePath]
: (statePath as TKnownStatePath<TState>[]);
const statePathsLookup: Record<
TKnownStatePath<TState>,
true
> = statePath.reduce((acc, path) => {
> = statePaths.reduce((acc, path) => {
acc[path] = true;
return acc;
}, {} as Record<TKnownStatePath<TState>, true>);
registerStateChangedCallback<TState, TAction>({
callback: ({ changedPaths, newState }) => {
callback: ({ action, changedPaths, newState, oldState }) => {
/**
* Prevent receiving this React warning
* "Can't perform a React state update on an unmounted component.
Expand All @@ -79,15 +116,22 @@ export const useSelector = <TState extends Object, TAction extends Action>({
) {
setCurrentState(newState);
}
if (callback) {
callback({ action, changedPaths, newState, oldState });
}
},
lateInvoke: typeof lateInvoke === "boolean" ? lateInvoke : true,
listenerId: listenerIdRef.current,
containerId,
lateInvoke,
listenerId: listenerIdRef.current,
statePath: "*",
});
return () => {
if (switchOff) {
return;
}
unregisterStateChangedCallback<TState>({
containerId,
lateInvoke,
listenerId: listenerIdRef.current,
statePath: "*",
});
Expand Down