Skip to content

Commit

Permalink
change dispatchRef to mutableRefObject
Browse files Browse the repository at this point in the history
  • Loading branch information
mtinner committed Oct 24, 2019
1 parent 2b30566 commit 0c20fb9
Showing 1 changed file with 9 additions and 13 deletions.
22 changes: 9 additions & 13 deletions src/createReducer.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,24 @@
import { useCallback, useRef, useState } from 'react';
import { MutableRefObject, useCallback, useRef, useState } from 'react';
import useUpdateEffect from './useUpdateEffect';

type Dispatch<Action> = (action: Action) => void;

type Store<Action, State> = {
interface Store<Action, State> {
getState: () => State;
dispatch: Dispatch<Action>;
};
}

type Middleware<Action, State> = (
store: Store<Action, State>
) => (next: Dispatch<Action>) => (action: Action) => void;
type Middleware<Action, State> = (store: Store<Action, State>) => (next: Dispatch<Action>) => (action: Action) => void;

function composeMiddleware<Action, State>(chain: Middleware<Action, State>[]) {
function composeMiddleware<Action, State>(chain: Array<Middleware<Action, State>>) {
return (context: Store<Action, State>, dispatch: Dispatch<Action>) => {
return chain.reduceRight((res, middleware) => {
return middleware(context)(res);
}, dispatch);
};
}

const createReducer = <Action, State>(
...middlewares: Middleware<Action, State>[]
) => {
const createReducer = <Action, State>(...middlewares: Array<Middleware<Action, State>>) => {
const composedMiddleware = composeMiddleware<Action, State>(middlewares);

return (
Expand All @@ -42,11 +38,11 @@ const createReducer = <Action, State>(
[reducer]
);

const dispatchRef: { current: Dispatch<Action> } = useRef(
const dispatchRef: MutableRefObject<Dispatch<Action>> = useRef(
composedMiddleware(
{
getState: () => ref.current,
dispatch: (...args: [Action]) => dispatchRef.current(...args)
dispatch: (...args: [Action]) => dispatchRef.current(...args),
},
dispatch
)
Expand All @@ -56,7 +52,7 @@ const createReducer = <Action, State>(
dispatchRef.current = composedMiddleware(
{
getState: () => ref.current,
dispatch: (...args: [Action]) => dispatchRef.current(...args)
dispatch: (...args: [Action]) => dispatchRef.current(...args),
},
dispatch
);
Expand Down

0 comments on commit 0c20fb9

Please sign in to comment.