Skip to content

Commit

Permalink
fix: makeReactive not updating props on rerender
Browse files Browse the repository at this point in the history
  • Loading branch information
hlysine committed Jun 1, 2023
1 parent 01b41b1 commit 623bc6f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
13 changes: 13 additions & 0 deletions src/__tests__/component.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@ describe('makeReactive', () => {
const content = await findByText('Test component');
expect(content).toBeTruthy();
});
it('updates props', async () => {
const Tester = makeReactive(function Tester({ value }: { value: string }) {
return <p>{value}</p>;
});

const { findByText, rerender } = render(<Tester value="Test component" />);
const content = await findByText('Test component');
expect(content).toBeTruthy();

rerender(<Tester value="Test component 2" />);
const content2 = await findByText('Test component 2');
expect(content2).toBeTruthy();
});
it('re-renders when ref changes', async () => {
const count = ref(0);
const Tester = makeReactive(function Tester() {
Expand Down
16 changes: 11 additions & 5 deletions src/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { useEffect, useRef, useState } from 'react';
interface ComponentReactivity {
scope: EffectScope;
effect: ReactiveEffectRunner;
args: [props: any, ctx?: any];
}

const renderedComponents = new WeakMap<any, ComponentReactivity>();
Expand Down Expand Up @@ -46,7 +47,7 @@ const renderedComponents = new WeakMap<any, ComponentReactivity>();
export const makeReactive = <P extends {}>(
component: React.FC<P>
): React.FC<P> => {
const ReactiveFC: React.FC<P> = (props, ctx) => {
const ReactiveFC: React.FC<P> = (...args) => {
const reactivityRef = useRef<ComponentReactivity | null>(null);
const [, setTick] = useState(0);
const rerender = () => setTick((v) => v + 1);
Expand All @@ -55,13 +56,17 @@ export const makeReactive = <P extends {}>(
if (reactivityRef.current === null) {
const scope = effectScope();
scope.run(() => {
const runner = effect(() => component(props, ctx), {
lazy: true,
scheduler: rerender,
});
const runner = effect(
() => component(...reactivityRef.current!.args),
{
lazy: true,
scheduler: rerender,
}
);
reactivityRef.current = {
scope,
effect: runner,
args,
};
});
if (requiresRerender) {
Expand Down Expand Up @@ -96,6 +101,7 @@ export const makeReactive = <P extends {}>(
renderedComponents.set(fiber, reactivityRef.current!);
}

reactivityRef.current!.args = args;
return reactivityRef.current!.scope.run(() =>
reactivityRef.current!.effect()
);
Expand Down

0 comments on commit 623bc6f

Please sign in to comment.