Skip to content
This repository was archived by the owner on Sep 14, 2023. It is now read-only.

feat: connectAtom HOC for class components #107

Open
wants to merge 4 commits into
base: master
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
17 changes: 15 additions & 2 deletions src/react-atom-internal.ts → src/react-atom-internal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
setValidator,
swap
} from "@libre/atom";
import { SetStateAction, useLayoutEffect, useMemo, useState } from "react";
import React, { SetStateAction, useLayoutEffect, useMemo, useState } from "react";

import * as ErrorMsgs from "./error-messages";
import { HookDependencies, PublicExports, ReactUseStateHook, UseAtomOptions } from "./internal-types";
Expand Down Expand Up @@ -77,7 +77,7 @@ export function initialize(hooks: HookDependencies): PublicExports {
let hook: ReactUseStateHook<S | R>;
try {
selector = useMemo(() => memoLast(selector), [select]);
[, hook] = useState({}) as [{}, ReactUseStateHook<S | R>];
[, hook] = (useState({}) as unknown) as [{}, ReactUseStateHook<S | R>];
} catch (err) {
throw new TypeError(ErrorMsgs.calledUseAtomOutsideFunctionComponent);
}
Expand Down Expand Up @@ -186,6 +186,19 @@ export function useAtom<S, R>(atom: Atom<S>, options?: UseAtomOptions<S, R>) {
return select ? internalUseAtom(atom, { select }) : internalUseAtom(atom);
}

// =========================== CONNECTATOM ====================================
export function connectAtom<A, S>(atom: Atom<A>, mapStateToProps: (state: A) => S) {
return function<P>(Component: React.ComponentType<S & P>) {
const wrapper: React.FC<P> = (props: P) => {
const state = useAtom(atom);
const stateProps = mapStateToProps(state);
return <Component {...stateProps} {...props} />;
};

return wrapper;
};
}

/**
* default instance of useAtom
*/
Expand Down
98 changes: 98 additions & 0 deletions test/connectAtom.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { connectAtom } from "../src/react-atom-internal";
import * as React from "react";
import { Atom, deref, swap } from "@libre/atom";
import { cleanup, render, getByTestId } from "react-testing-library";
import { act } from "react-dom/test-utils";

interface ITestAtom {
count: number;
notACount: string;
}

interface ITestProps {
testProp: string;
}

interface ITestStateProps {
countFromState: number;
}

const TEST_ATOM = Atom.of<ITestAtom>({ count: 3, notACount: "kek" });
let timesRendered = 0;

class TestComponent extends React.Component<ITestProps & ITestStateProps> {
render() {
timesRendered += 1;
const props = this.props;
return (
<div>
<p data-testid="testProp">{props.testProp}</p>
<p data-testid="countFromState">{props.countFromState}</p>
</div>
);
}
}

describe("connectAtom function", () => {
afterEach(() => {
// WARNING! DON'T CHANGE THE ORDER OF THESE:
timesRendered = 0;
cleanup();
// END WARNING
});

it("connectAtom is a function", () => {
expect(connectAtom).toBeInstanceOf(Function);
});

it("should connect atom to class component without errors", () => {
connectAtom(TEST_ATOM, state => ({ countFromState: state.count }))(TestComponent);
});

it("returns the state of the connected atom", () => {
const ConnectedComponent = connectAtom(TEST_ATOM, state => ({ countFromState: state.count }))(TestComponent);
const { container } = render(<ConnectedComponent testProp="test prop" />);
const actualCountFromState = getByTestId(container, "countFromState").textContent;
const expectedCountFromState = deref(TEST_ATOM).count.toString();

expect(actualCountFromState).toBe(expectedCountFromState);
});

it("returns component props", () => {
const ConnectedComponent = connectAtom(TEST_ATOM, state => ({ countFromState: state.count }))(TestComponent);
const expectedTestProp = "test prop";
const { container } = render(<ConnectedComponent testProp="test prop" />);
const actualTestProp = getByTestId(container, "testProp").textContent;

expect(actualTestProp).toBe(expectedTestProp);
});

it("returns the same values across multiple renders", () => {
const ConnectedComponent = connectAtom(TEST_ATOM, state => ({ countFromState: state.count }))(TestComponent);
const { container, rerender } = render(<ConnectedComponent testProp="test prop" />);
const statePropValue = getByTestId(container, "countFromState").textContent;
const propValue = getByTestId(container, "testProp").textContent;

for (let i = 0; i < 10; i++) {
rerender(<ConnectedComponent testProp="test prop" />);
let statePropValueAfterRerender = getByTestId(container, "countFromState").textContent;
let propValueAfterRerender = getByTestId(container, "testProp").textContent;
expect(statePropValueAfterRerender).toBe(statePropValue);
expect(propValueAfterRerender).toBe(propValue);
}
});

it("returns changed state of the atom after swap", () => {
const ConnectedComponent = connectAtom(TEST_ATOM, state => ({ countFromState: state.count }))(TestComponent);
const { container } = render(<ConnectedComponent testProp="string" />);
let actualCountFromState = getByTestId(container, "countFromState").textContent;
let expectedCountFromState = deref(TEST_ATOM).count.toString();
expect(actualCountFromState).toBe(expectedCountFromState);
act(() => {
swap(TEST_ATOM, state => ({ ...state, count: 8 }));
});
actualCountFromState = getByTestId(container, "countFromState").textContent;
expectedCountFromState = deref(TEST_ATOM).count.toString();
expect(actualCountFromState).toBe(expectedCountFromState);
});
});
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@
"target": "es5",
"typeRoots": ["node_modules/@types"]
},
"include": ["src/**/*.ts"]
"include": ["src/**/*.ts", "src/react-atom-internal.tsx"]
}