Skip to content

Instantly share code, notes, and snippets.

@hadnazzar
Created February 28, 2020 11:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadnazzar/a7c7b46c4a9a0f572451003795273e8a to your computer and use it in GitHub Desktop.
Save hadnazzar/a7c7b46c4a9a0f572451003795273e8a to your computer and use it in GitHub Desktop.
import React, { useState, useEffect, useCallback } from 'react';
import { useFormikContext } from 'formik';
import _ from 'lodash';
const AutoSave = ({ debounceMs = 1000 }) => {
const formik = useFormikContext();
const [isSaved, setIsSaved] = useState(null);
const debouncedSubmit = useCallback(
_.debounce(() => {
return formik.submitForm().then(() => setIsSaved(true));
}, debounceMs),
[formik.submitForm, debounceMs],
);
useEffect(() => debouncedSubmit, [debouncedSubmit, formik.values]);
return (
<p className="text-center text-success">
{!!formik.isSubmitting
? 'Saving...'
: isSaved
? 'Your changes saved.'
: null}
</p>
);
};
export default AutoSave;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment