Skip to content

Feature/extending with use enhanced selector #4

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
},
"homepage": "https://github.com/WealthArc/key-value-state-container#readme",
"dependencies": {
"key-value-state-container": "^1.0.0",
"key-value-state-container": "~1.0.0",
"lodash": "^4.17.4",
"react": "^18.2.0"
},
Expand Down
21 changes: 21 additions & 0 deletions src/tests/GameManaComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React from "react";
import { RendersWithContainerId } from "../types/contracts";
import { State } from "./state-container/game-logic";
import { useEnhancedSelector } from "../use-enhanced-selector";

interface Props extends RendersWithContainerId {}

export const GameManaComponent = ({ containerId }: Props) => {
const renderedRef = React.useRef<number>(0);
const mana = useEnhancedSelector<State, number>({
containerId,
selector: ({ header }) => header.mana,
})();
renderedRef.current = renderedRef.current + 1;
return (
<div>
<div data-testid="mana">Mana: {mana}</div>
<div data-testid="rendered">Rendered: {renderedRef.current}</div>
</div>
);
};
12 changes: 10 additions & 2 deletions src/tests/SumComponent.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import React from "react";
import { useSelector } from "../use-selector";
import { RendersWithContainerId } from "../types/contracts";
import { Action, State } from "./state-container/enhanced-logic";
import {
Action,
State,
} from "./state-container/increment-decrement-container-logic";

export interface RendersWithListeningToPath {
path: keyof State | "*";
Expand All @@ -16,5 +19,10 @@ export const SumComponent = ({ containerId, path }: Props) => {
statePath: [path],
});
renderedRef.current = renderedRef.current + 1;
return <div data-testid="sum">The sum is: {sum}</div>;
return (
<div>
<div data-testid="sum">The sum is: {sum}</div>
<div data-testid="rendered">Rendered: {renderedRef.current}</div>
</div>
);
};
63 changes: 63 additions & 0 deletions src/tests/state-container/game-logic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* The enhanced logic adds a special action `zero` that bypasses the reducer.
*/
import { dispatchAction, Reducer } from "key-value-state-container";

export type Action = {
name: "use-mana";
payload: number;
};

/**
* Header as displayed on the screen
*/
type Header = {
/**
* Mana points.
*/
mana: number;

/**
* The score of the user.
*/
score: number;
};

export type State = {
header: Header;
};

export const reducer: Reducer<State, Action> = async ({ state, action }) => {
switch (action.name) {
case "use-mana": {
return {
...state,
header: {
...state.header,
mana: state.header.mana - action.payload,
},
};
}
default: {
return state;
}
}
};

export const dispatchActions = ({
containerId,
randomArray,
}: {
containerId: string;
randomArray: number[];
}) => {
for (let i = 0; i < randomArray.length; i++) {
dispatchAction<State, Action>({
action: {
name: "use-mana",
payload: randomArray[i],
},
containerId,
});
}
};
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@

/**
* The enhanced logic adds a special action `zero` that bypasses the reducer.
*/
import { dispatchAction, Reducer } from "key-value-state-container";

export type Action =
Expand All @@ -26,6 +23,7 @@ export type Action =

export type State = {
sum: number;

/**
* How many times the `increment` action has been dispatched.
*/
Expand Down
46 changes: 46 additions & 0 deletions src/tests/use-game-mana-selector.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import _ from "lodash";
import React from "react";

import { render, act } from "@testing-library/react";
import { finishedProcessingQueue } from "key-value-state-container";

import { reducer, dispatchActions } from "./state-container/game-logic";
import { ContainerRoot } from "../ContainerRoot";
import { GameManaComponent } from "./GameManaComponent";

const containerId = "use-enhanced-selector-state-container";
const initialMana = 1000;

test("useGameManaSelector test", async () => {
/**
* Mana spent for fighting monsters 👾.
*/
const manaSpentRandomArray = Array.from({ length: 25 }, () => _.random(1, 8));
const expectedManaLeft = manaSpentRandomArray.reduce(
(acc, el) => acc - el,
initialMana
);
const { getByTestId, unmount } = render(
<ContainerRoot
initialState={{
header: {
mana: initialMana,
score: 500,
},
}}
containerId={containerId}
reducer={reducer}
>
<GameManaComponent containerId={containerId} />
</ContainerRoot>
);
await act(async () => {
dispatchActions({ containerId, randomArray: manaSpentRandomArray });
await finishedProcessingQueue({ containerId });
});
expect(getByTestId("mana").innerHTML).toEqual(`Mana: ${expectedManaLeft}`);
expect(getByTestId("rendered").innerHTML).toEqual("Rendered: 2");
act(() => {
unmount();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import React from "react";
import { render, act } from "@testing-library/react";
import { finishedProcessingQueue } from "key-value-state-container";

import { reducer, dispatchActions } from "./state-container/enhanced-logic";
import {
reducer,
dispatchActions,
} from "./state-container/increment-decrement-container-logic";
import { RendersWithListeningToPath, SumComponent } from "./SumComponent";
import { ContainerRoot } from "../ContainerRoot";

Expand All @@ -27,6 +30,7 @@ const useSelectorTest = async ({ path }: RendersWithListeningToPath) => {
await finishedProcessingQueue({ containerId });
});
expect(getByTestId("sum").innerHTML).toEqual(`The sum is: ${expectedSum}`);
expect(getByTestId("rendered").innerHTML).toEqual("Rendered: 2");
act(() => {
unmount();
});
Expand Down
7 changes: 5 additions & 2 deletions src/types/contracts/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@


export * from "./renders-with-container-id";
export * from "./selector";
export * from "./use-dispatch-action";
export * from "./use-get-container-id";
export * from "./use-selector";
export * from "./renders-with-container-id";
export * from "./use-selector";
31 changes: 31 additions & 0 deletions src/types/contracts/selector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
The MIT License (MIT)

Copyright Tomasz Szatkowski, Patryk Parcheta
WealthArc https://www.wealtharc.com (c) 2023, 2024

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/**
* Unfortunately, the returned type has to be manually declared.
*/
export type Selector<TState extends Object, TResult> = (
state: TState
) => TResult;
93 changes: 93 additions & 0 deletions src/use-enhanced-selector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/**
The MIT License (MIT)

Copyright Tomasz Szatkowski, Patryk Parcheta
WealthArc https://www.wealtharc.com (c) 2023, 2024

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import {
getContainer,
getUniqueId,
registerStateChangedCallback,
unregisterStateChangedCallback,
} from "key-value-state-container";
import { useCallback, useEffect, useRef, useState } from "react";
import { Selector } from "types/contracts";

type Args<TState extends Object, TResult> = {
containerId: string;
selector: Selector<TState, TResult>;
lateInvoke?: boolean;
};

export const useEnhancedSelector =
<TState extends Object, TResult>({
selector,
containerId,
lateInvoke,
}: Args<TState, TResult>) =>
(): TResult => {
const listenerIdRef = useRef(getUniqueId());

const memoizedSelector = useCallback(selector, []);

const [selectedState, setSelectedState] = useState<ReturnType<any>>(() => {
return memoizedSelector(
getContainer<TState>({
containerId,
ignoreUnregistered: true,
})
);
});

useEffect(() => {
const listenerId = listenerIdRef.current;
const lateInvokeValue =
typeof lateInvoke === "undefined" ? true : lateInvoke;

registerStateChangedCallback<TState, any>({
callback: ({ newState }) => {
const newSelectValue = memoizedSelector(newState);

if (
JSON.stringify(selectedState) !== JSON.stringify(newSelectValue)
) {
setSelectedState(newSelectValue);
}
},
listenerId,
containerId,
lateInvoke: lateInvokeValue,
statePath: "*",
});

return () => {
unregisterStateChangedCallback({
containerId,
lateInvoke: lateInvokeValue,
listenerId,
statePath: "*",
});
};
}, [memoizedSelector, selectedState]);

return selectedState;
};