Skip to content

Commit d42dfe9

Browse files
committed
feat: add local storage
1 parent 1fe8087 commit d42dfe9

File tree

3 files changed

+31
-4
lines changed

3 files changed

+31
-4
lines changed

src/components/terminal/TerminalBody.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { v4 as uuidv4 } from "uuid";
77
import parse from "html-react-parser";
88
import { useUsernameContext } from "../../context/UsernameContext";
99
import { getCommandResponse, MOTD } from "../../lib/commands";
10+
import { useLocalStorage } from "../../hooks/useLocalStorage";
1011

1112
interface TerminalBodyProps {}
1213

@@ -15,7 +16,10 @@ const TerminalBody: FC<TerminalBodyProps> = () => {
1516

1617
const [history, setHistory] = useState<History[]>([]);
1718
const [motdVisible, setMotdVisible] = useState(true);
18-
const [commandHistory, setCommandHistory] = useState<string[]>([]);
19+
const [commandHistory, setCommandHistory] = useLocalStorage<string[]>(
20+
"commandHistory",
21+
[]
22+
);
1923

2024
const scrollToRef = useRef<HTMLDivElement>(null);
2125

src/context/UsernameContext.tsx

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ import {
33
FC,
44
PropsWithChildren,
55
useContext,
6-
useState,
6+
useEffect,
77
} from "react";
8+
import { useLocalStorage } from "../hooks/useLocalStorage";
89

910
interface UsernameContextType {
1011
username: string;
@@ -30,14 +31,17 @@ interface UsernameContextProviderProps extends PropsWithChildren {}
3031
const UsernameContextProvider: FC<UsernameContextProviderProps> = ({
3132
children,
3233
}) => {
33-
const [username, setUsername] = useState("root");
34+
const [username, setUsername] = useLocalStorage("username", "root");
3435

3536
function handleUsernameChange(possibleUsername?: string | null) {
3637
const newUsername = possibleUsername || "root";
3738
setUsername(newUsername);
38-
document.title = `${newUsername}@kali: ~`;
3939
}
4040

41+
useEffect(() => {
42+
document.title = `${username}@kali: ~`;
43+
}, [username]);
44+
4145
return (
4246
<UsernameContext.Provider
4347
value={{ username, setUsername: handleUsernameChange }}

src/hooks/useLocalStorage.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
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+
}

0 commit comments

Comments
 (0)