<commit_before>import { useEffect, useState } from 'react';
import { ActorRef, Interpreter, Subscribable } from 'xstate';
import { isActorWithState } from './useActor';
import { getServiceSnapshot } from './useService';

function isService(actor: any): actor is Interpreter<any, any, any, any> {
  return 'state' in actor && 'machine' in actor;
}

export function useSelector<
  TActor extends ActorRef<any, any>,
  T,
  TEmitted = TActor extends Subscribable<infer Emitted> ? Emitted : never
>(
  actor: TActor,
  selector: (emitted: TEmitted) => T,
  compare: (a: T, b: T) => boolean = (a, b) => a === b,
  getSnapshot: (a: TActor) => TEmitted = (a) =>
    isService(a)
      ? getServiceSnapshot(a)
      : isActorWithState(a)
      ? a.state
      : undefined
) {
  const [selected, setSelected] = useState(() => selector(getSnapshot(actor)));

  useEffect(() => {
    const sub = actor.subscribe((emitted) => {
      const nextSelected = selector(emitted);
      if (!compare(selected, nextSelected)) {
        setSelected(nextSelected);
      }
    });

    return () => sub.unsubscribe();
  });

  return selected;
}<commit_msg>Fix selector subscription<commit_after>import { useEffect, useState } from 'react';
import { ActorRef, Interpreter, Subscribable } from 'xstate';
import { isActorWithState } from './useActor';
import { getServiceSnapshot } from './useService';

function isService(actor: any): actor is Interpreter<any, any, any, any> {
  return 'state' in actor && 'machine' in actor;
}

const defaultCompare = (a, b) => a === b;

export function useSelector<
  TActor extends ActorRef<any, any>,
  T,
  TEmitted = TActor extends Subscribable<infer Emitted> ? Emitted : never
>(
  actor: TActor,
  selector: (emitted: TEmitted) => T,
  compare: (a: T, b: T) => boolean = defaultCompare,
  getSnapshot: (a: TActor) => TEmitted = (a) =>
    isService(a)
      ? getServiceSnapshot(a)
      : isActorWithState(a)
      ? a.state
      : undefined
) {
  const [selected, setSelected] = useState(() => selector(getSnapshot(actor)));

  useEffect(() => {
    const sub = actor.subscribe((emitted) => {
      const nextSelected = selector(emitted);
      if (!compare(selected, nextSelected)) {
        setSelected(nextSelected);
      }
    });

    return () => sub.unsubscribe();
  }, [selector]);

  return selected;
}
{'fraction_non_alphanumeric': 0.149528706083976, 'fraction_numerical': 0.0, 'mean_word_length': 3.7556008146639512, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6426067', 'n_tokens_mistral': 737, 'n_tokens_neox': 725, 'n_words': 198}