Skip to content

Commit

Permalink
WebStorageを使用して入力内容をブラウザに保存
Browse files Browse the repository at this point in the history
  • Loading branch information
s-yoshiii committed Mar 20, 2022
1 parent 8a1ce8b commit a55fe30
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
13 changes: 13 additions & 0 deletions src/hooks/use_state_with_storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useState } from 'react';

export const useStateWithStorage = (
init: string,
key: string
): [string, (s: string) => void] => {
const [value, setValue] = useState<string>(localStorage.getItem(key) || init);
const setValueWithStrage = (nextValue: string): void => {
setValue(nextValue);
localStorage.setItem(key, nextValue);
};
return [value, setValueWithStrage];
};
7 changes: 2 additions & 5 deletions src/pages/editor.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { Box, Flex, Textarea } from '@chakra-ui/react';
import * as React from 'react';
const { useState } = React;
import { useStateWithStorage } from '../hooks/use_state_with_storage';
import { Header } from '../components/header';
const StorageKey = 'pages/editor:textarea';
export const Editor: React.FC = () => {
const [text, setText] = useState<string>(
localStorage.getItem(StorageKey) || ''
);
const [text, setText] = useStateWithStorage('', StorageKey);
return (
<>
<Header />
Expand All @@ -18,7 +16,6 @@ export const Editor: React.FC = () => {
height='100%'
variant='flushed'
p='3'
isInvalid
onChange={(e) => {
setText(e.target.value);
}}
Expand Down

0 comments on commit a55fe30

Please sign in to comment.