Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/chlbri/react-sync
https://github.com/chlbri/react-sync
Last synced: about 1 month ago
JSON representation
- Host: GitHub
- URL: https://github.com/chlbri/react-sync
- Owner: chlbri
- License: mit
- Created: 2024-05-21T19:06:32.000Z (8 months ago)
- Default Branch: main
- Last Pushed: 2024-05-21T19:25:54.000Z (8 months ago)
- Last Synced: 2024-11-29T04:51:55.273Z (about 2 months ago)
- Language: TypeScript
- Size: 63.5 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
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]);
// #endregionconst selectedSnapshot = useSync(
subscribe,
boundGetSnapshot,
boundGetSnapshot,
selector,
compare,
);return selectedSnapshot;
}
```