{"size": 833, "ext": "js", "max_stars_repo_path": "client/src/components/DocumentEditor/AutoSave.js", "max_stars_repo_name": "sibartlett/methodical", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "client/src/components/DocumentEditor/AutoSave.js", "max_issues_repo_name": "sibartlett/methodical", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "client/src/components/DocumentEditor/AutoSave.js", "max_forks_repo_name": "sibartlett/methodical", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.1388888889, "max_line_length": 75, "alphanum_fraction": 0.5870348139}
import { useEffect, useState } from "react";
import { debounce, isEqual } from "lodash-es";
import { connect as formConnect } from "formik";

const preSave = debounce(({ initialValues, values }, callback) => {
  if (!isEqual(initialValues, values)) {
    callback();
  }
}, 600);

const AutoSave = ({ formik: { initialValues, values }, render, save }) => {
  const [isSaving, setSaving ] = useState(false);
  const [saveError, setError ] = useState();

  const onSave = () => {
    setSaving(true);

    save(values)
      .then(() => {
        setError();
      })
      .catch(error => {
        setError(error);
      })
      .then(() => {
        setSaving(false);
      });
  };

  useEffect(() => preSave({ initialValues, values}, onSave));

  return render({ isSaving, saveError });
};

export default formConnect(AutoSave);
