Skip to content

Instantly share code, notes, and snippets.

@jimmycallin
Created November 27, 2018 18:06
Show Gist options
  • Save jimmycallin/8f387fccfe2ab590b15917bf31692904 to your computer and use it in GitHub Desktop.
Save jimmycallin/8f387fccfe2ab590b15917bf31692904 to your computer and use it in GitHub Desktop.
Sick and bored makes a perfect opportunity to learn React Hooks! Implemented a very simple form state manager with autosave and debounce which covers about 80% of what we need at work.
import React, { useEffect, useState } from "react";
const useAutosave = (handleSave, debounceTimeout) => {
const [mounted, setMounted] = useState(false);
const [formValues, setFormValues] = useState({});
const [lastSaved, setLastSaved] = useState({});
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
const timeout = setTimeout(async () => {
if (!mounted) return setMounted(true);
setSubmitting(true);
await handleSave(formValues);
setLastSaved(formValues);
setSubmitting(false);
}, debounceTimeout);
return () => clearTimeout(timeout);
}, [formValues]);
return [(e) => setFormValues({ ...formValues, [e.target.name]: e.target.value }),
submitting,
lastSaved];
};
const handleSave = (values) => new Promise((resolve) => setTimeout(resolve, 1000));
export default () => {
const [handleFormChange, submitting, lastSaved] = useAutosave(handleSave, 1000);
return (
<div className="App">
<div>
<div><input name="first" onChange={handleFormChange} /></div>
<div><input name="second" onChange={handleFormChange} /></div>
</div>
<div style={{ marginTop: "20px" }}>
{Object.keys(lastSaved).length > 0 && JSON.stringify(lastSaved, null, 2)}
</div>
<div>{submitting && "Saving..."}</div>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment