Skip to content
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

Improvement: Unit of work for "observable" #1

Open
betula opened this issue Jan 22, 2024 · 0 comments
Open

Improvement: Unit of work for "observable" #1

betula opened this issue Jan 22, 2024 · 0 comments

Comments

@betula
Copy link
Owner

betula commented Jan 22, 2024

import { autorun } from 'mobx';
import { FunctionComponent, memo, NamedExoticComponent, useRef, useState } from 'react';

type State = {
  scheduled?: boolean;
  unsubscriber?: () => void;
};

export function observer<T extends object>(Comp: FunctionComponent<T>): NamedExoticComponent<T>;
export function observer<T extends object>(
  Comp: FunctionComponent<T>,
  options: { forwardRef: true },
): FunctionComponent<T>;
export function observer<T extends object>(
  Comp: FunctionComponent<T>,
  options?: { forwardRef: boolean },
): FunctionComponent<T> | NamedExoticComponent<T> {
  return options?.forwardRef ? ObserveInner : (memo(ObserveInner) as unknown as NamedExoticComponent<T>);

  function ObserveInner(this: unknown, props: T, contextOrForwardedRef?: unknown) {
    const [_, forceUpdate] = useState<object>();
    const stateRef = useRef<State>();

    if (!stateRef.current) {
      stateRef.current = {};
    }
    const state = stateRef.current;

    if (state.unsubscriber) {
      state.unsubscriber();
    }
    let runned = false;
    let ret;
    state.unsubscriber = autorun(() => {
      if (runned) {
        if (!state.scheduled) {
          state.scheduled = true;
          queueMicrotask(() => {
            state.scheduled = false;
            forceUpdate({});
          });
        }
      } else {
        runned = true;
        ret = Comp.call(this, props, contextOrForwardedRef);
      }
    });

    return ret;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant