import { useEffect, useRef } from 'react';
import { UseMutationResult } from 'react-query';

export const useMutationOnMount = (
  mutation: UseMutationResult<any, any, any, any>,
  id?: string | number,
) => {
  const currentId = useRef(id);
  const isMounted = useRef(false);

  useEffect(() => {
    if (currentId.current !== id) {
      currentId.current = id;
      isMounted.current = false;
    }

    if (isMounted.current) return;
    isMounted.current = true;
    mutation.mutate(mutation.variables);
  }, [mutation, id]);
};
