Skip to content

Instantly share code, notes, and snippets.

@dialguiba
Last active February 11, 2022 14:36
Show Gist options
  • Save dialguiba/4d38bbebc6b622b3fe923f2005741c2c to your computer and use it in GitHub Desktop.
Save dialguiba/4d38bbebc6b622b3fe923f2005741c2c to your computer and use it in GitHub Desktop.
react-hooks

Custom Hook: UseForm

Use:

const [formTodoValues, handleTodoInputChange] = useForm({
    name: "",
    date: moment(new Date()).format("YYYY-MM-DD"),
    description: "",
  });

const { name, date, description } = formTodoValues;

....

<Form.Control type="text" placeholder="Ingresa nombre de la tarea" value={name} name="name" onChange={handleTodoInputChange} />

important: name, value and onChange are necessary

// ****************************
// ************ Hook **********
// ****************************
import { useState } from "react";
export const useForm = (initialState = {}) => {
const [values, setValues] = useState(initialState);
const reset = () => {
setValues(initialState);
};
const handleInputChange = ({ target }) => {
setValues({
...values,
[target.name]: target.value,
});
};
return [values, handleInputChange, reset];
};
// ****************************
// ************ Hook **********
// ****************************
const usePersistedState = (defaultValue, key, source = localStorage) => {
const [value, setValue] = useState(() => {
const storageValue = source.getItem(key);
return storageValue !== null ? JSON.parse(storageValue) : defaultValue;
});
useEffect(() => {
source.setItem(key, JSON.stringify(value));
}, [source, key, value])
return [value, setValue];
}
export const usePersistedLocalStorageState = (defaultValue, key) => usePersistedState(defaultValue, key, localStorage)
export const usePersistedSessionStorageState = (defaultValue, key) =>
usePersistedState(defaultValue, key, sessionStorage)
// ****************************
// ****** How To Use It *******
// ****************************
import {usePersistedSessionStorageState, usePersistedLocalStorageState} from "./usePersistedStateFactory";
export default function App() {
const [localStorageValue] = usePersistedLocalStorageState("Hello", "hello-key")
const [sessionStorageValue] = usePersistedSessionStorageState("World", "world-key")
return (
<div className="App">
<p>LocalStorage value is: {localStorageValue}</p>
<p>SessionStorage value is: {sessionStorageValue}</p>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment