File tree Expand file tree Collapse file tree 3 files changed +31
-4
lines changed Expand file tree Collapse file tree 3 files changed +31
-4
lines changed Original file line number Diff line number Diff line change @@ -7,6 +7,7 @@ import { v4 as uuidv4 } from "uuid";
7
7
import parse from "html-react-parser" ;
8
8
import { useUsernameContext } from "../../context/UsernameContext" ;
9
9
import { getCommandResponse , MOTD } from "../../lib/commands" ;
10
+ import { useLocalStorage } from "../../hooks/useLocalStorage" ;
10
11
11
12
interface TerminalBodyProps { }
12
13
@@ -15,7 +16,10 @@ const TerminalBody: FC<TerminalBodyProps> = () => {
15
16
16
17
const [ history , setHistory ] = useState < History [ ] > ( [ ] ) ;
17
18
const [ motdVisible , setMotdVisible ] = useState ( true ) ;
18
- const [ commandHistory , setCommandHistory ] = useState < string [ ] > ( [ ] ) ;
19
+ const [ commandHistory , setCommandHistory ] = useLocalStorage < string [ ] > (
20
+ "commandHistory" ,
21
+ [ ]
22
+ ) ;
19
23
20
24
const scrollToRef = useRef < HTMLDivElement > ( null ) ;
21
25
Original file line number Diff line number Diff line change 3
3
FC ,
4
4
PropsWithChildren ,
5
5
useContext ,
6
- useState ,
6
+ useEffect ,
7
7
} from "react" ;
8
+ import { useLocalStorage } from "../hooks/useLocalStorage" ;
8
9
9
10
interface UsernameContextType {
10
11
username : string ;
@@ -30,14 +31,17 @@ interface UsernameContextProviderProps extends PropsWithChildren {}
30
31
const UsernameContextProvider : FC < UsernameContextProviderProps > = ( {
31
32
children,
32
33
} ) => {
33
- const [ username , setUsername ] = useState ( "root" ) ;
34
+ const [ username , setUsername ] = useLocalStorage ( "username" , "root" ) ;
34
35
35
36
function handleUsernameChange ( possibleUsername ?: string | null ) {
36
37
const newUsername = possibleUsername || "root" ;
37
38
setUsername ( newUsername ) ;
38
- document . title = `${ newUsername } @kali: ~` ;
39
39
}
40
40
41
+ useEffect ( ( ) => {
42
+ document . title = `${ username } @kali: ~` ;
43
+ } , [ username ] ) ;
44
+
41
45
return (
42
46
< UsernameContext . Provider
43
47
value = { { username, setUsername : handleUsernameChange } }
Original file line number Diff line number Diff line change
1
+ import { useEffect , useState } from "react" ;
2
+
3
+ export function useLocalStorage < T > ( key : string , defaultValue : T ) {
4
+ const [ value , setValue ] = useState < T > ( ( ) => {
5
+ try {
6
+ const item = localStorage . getItem ( key ) ;
7
+ return item ? JSON . parse ( item ) : defaultValue ;
8
+ } catch ( error ) {
9
+ console . error ( error ) ;
10
+ return defaultValue ;
11
+ }
12
+ } ) ;
13
+
14
+ useEffect ( ( ) => {
15
+ localStorage . setItem ( key , JSON . stringify ( value ) ) ;
16
+ } , [ value , key ] ) ;
17
+
18
+ return [ value , setValue ] as const ;
19
+ }
You can’t perform that action at this time.
0 commit comments