Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/chlbri/react-sync


https://github.com/chlbri/react-sync

Last synced: about 1 month ago
JSON representation

Awesome Lists containing this project

README

        

## Add better compatobolity to react state/store libraries

### Example of the xstate selector for react

```typescript
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useCallback, useRef } from 'react';
import type {
AnyState,
EventObject,
Interpreter,
State,
StateFrom,
Typestate,
} from 'xstate';
import { useSync } from '../hook';
import { defaultCompare, defaultSelector, getSnapShot } from './utils';

export default function useSelector<
TContext extends object,
TEvents extends EventObject = EventObject,
TTypestate extends Typestate = {
value: any;
context: TContext;
},
T = State,
>(
service: Interpreter,
selector: (
emitted: StateFrom<
Interpreter['machine']
>,
) => T = defaultSelector,
compare: (a: T, b: T) => boolean = defaultCompare,
): T {
const initialStateCacheRef = useRef();

type Listener = (
emitted: StateFrom<
Interpreter['machine']
>,
) => void;

// #region Hooks
const subscribe = useCallback(
(listerner?: Listener) => {
const { unsubscribe } = service.subscribe(listerner);
return unsubscribe;
},
[service],
);

const boundGetSnapshot = useCallback(() => {
return getSnapShot(
service,
initialStateCacheRef,
);
}, [service]);
// #endregion

const selectedSnapshot = useSync(
subscribe,
boundGetSnapshot,
boundGetSnapshot,
selector,
compare,
);

return selectedSnapshot;
}
```