export const useStore = (shouldListen = true): [StoreState, StoreDispatch] => {
const setState = useState(state)[1];
const dispatch: StoreDispatch = async ({ type, payload }) => {
const newState = await updatedState(type, payload)
state = { ...state, ...newState }
for (const listener of listeners) listener(state)
};
const listenerFilter = useCallback((listener: React.Dispatch<React.SetStateAction<StoreState>>): boolean => (
listener !== setState
), [setState]);
useEffect(() => {
pipe(shouldListen, B.fold(constVoid, () => listeners.push(setState)));
return () => {
listeners = pipe(
shouldListen,
O.fromPredicate(I.of),
O.map(() => pipe(listeners, A.filter(listenerFilter))),
O.getOrElse(() => listeners),
)
}
}, [setState, shouldListen]);
return [state, useCallback(dispatch, [])];
}
Senior Frontend Engineer specialized in creating complex single page applications and apps that scales.
TypeScript | React | Next.JS | GraphQL | Flutter
-
Freelance Software Engineer
- Remote
- https://andreaperinu.com/
- in/andrea-perinu
Block or Report
Block or report andreaperinu
Report abuse
Contact GitHub support about this user’s behavior. Learn more about reporting abuse.
Report abusePinned
Something went wrong, please refresh the page to try again.
If the problem persists, check the GitHub status page or contact support.
If the problem persists, check the GitHub status page or contact support.