import React, { useContext, useEffect, useRef } from "react";
import { IBulkEditProps } from "../IBulkEditProps";

const propsRefContext = React.createContext({});

// This provides an easy way to access the table props throughout the component
// tree if you don't care about rerendering.
export const usePropsRef = <TRow, TChange, TError>() =>
  useContext<React.MutableRefObject<IBulkEditProps<TRow, TChange, TError>>>(
    propsRefContext as unknown as React.Context<
      React.MutableRefObject<IBulkEditProps<TRow, TChange, TError>>
    >
  );

export const PropsRefProvider = <TRow, TChange, TError>({
  props,
  children,
}: {
  props: IBulkEditProps<TRow, TChange, TError>;
  children: React.ReactNode;
}) => {
  const propsRef = useRef(props);
  useEffect(() => {
    propsRef.current = props;
  }, [props]);

  return (
    <propsRefContext.Provider value={propsRef}>
      {children}
    </propsRefContext.Provider>
  );
};
