All files useMiddleware.js

100% Statements 12/12
100% Branches 1/1
100% Functions 5/5
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                        15x     15x   12x 12x 12x     15x 4x 1x     15x 15x   15x        
import { useState } from "react";
import compose from "./compose";
 
/**
 *
 * @param {Object} reducer a function which given a state and an action returns the next state
 * @param {*} initialState the initial state
 * @param {Array} middlewares an array of redux friendly middleware
 * @return {Array} A react Hook which you can consume in other React Function Components
 * the hooks is structured as [state, dispatch]
 */
function useMiddleware({ reducer, initialState, middlewares = [] }) {
  let [state, setState] = useState(initialState);
  let enhancedDispatch;
 
  const dispatch = action => {
    // mutation trick
    state = reducer(state, action);
    setState(state);
    return action;
  };
 
  const middlewareAPI = {
    getState: () => state,
    dispatch: (...args) => enhancedDispatch(...args)
  };
 
  const chain = middlewares.map(middleware => middleware(middlewareAPI));
  enhancedDispatch = compose(...chain)(dispatch);
 
  return [state, enhancedDispatch];
}
 
export default useMiddleware;