import React, { useReducer, useMemo } from "react";
import PropTypes from "prop-types";
import { NetworkStateContext, NetworkDispatchContext } from "./contexts";
import { reducer, dispatchActions as reducerDispatchActions } from "./reducer";
import { initialState } from "./initialState";

const NetworkStateProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const dispatchActions = useMemo(() => reducerDispatchActions(dispatch), [dispatch]);

  return (
    <NetworkStateContext.Provider value={state}>
      <NetworkDispatchContext.Provider value={dispatchActions}>{children}</NetworkDispatchContext.Provider>
    </NetworkStateContext.Provider>
  );
};

NetworkStateProvider.propTypes = {
  children: PropTypes.node.isRequired
};

export default NetworkStateProvider;
