Created
February 28, 2020 11:44
-
-
Save hadnazzar/a7c7b46c4a9a0f572451003795273e8a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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