Skip to content

Instantly share code, notes, and snippets.

@mitchallen
Last active December 16, 2021 21:27
Show Gist options
  • Save mitchallen/474766b8c12084c879d3ae27067e4944 to your computer and use it in GitHub Desktop.
Save mitchallen/474766b8c12084c879d3ae27067e4944 to your computer and use it in GitHub Desktop.
// File: UseLocalStorageTextInput.tsx
// Author: Mitch Allen
import {ChangeEventHandler, useCallback, useState} from "react";
export interface LocalStorageTextInput {
storageKey?: string,
id?: string,
name?: string,
label?: string,
helperText?: string,
init?: string,
}
export interface LocalStorageTextInputProps {
id?: string,
name?: string,
label?: string,
value: string,
onChange: ChangeEventHandler<HTMLTextAreaElement | HTMLInputElement> | undefined,
helperText?: string,
}
export function useLocalStorageTextInput(options: LocalStorageTextInput = {}): LocalStorageTextInputProps {
let {
storageKey = undefined,
id = undefined,
name = undefined,
label = 'Text',
helperText = undefined,
init = '',
} = options;
if (name === undefined) {
name = id;
}
if( storageKey !== undefined ) {
init = localStorage.getItem( storageKey ) || init;
}
const [value, setValue] = useState(init);
const onChange = useCallback((event) => {
setValue(event.target.value);
if( storageKey ) {
localStorage.setItem( storageKey, event.target.value );
}
}, [storageKey]);
return {
id,
name,
label,
value,
onChange,
helperText,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment