Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improved the useLocalStorage hook to Handle Multiple Keys #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions videos/long/custom-react-hooks-useLocalStorage/index.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
import { useState } from 'react';
import { useState } from "react";

import { useLocalStorage } from './useLocalStorage';
import { useLocalStorage } from "./useLocalStorage";

const Demo = () => {
const [value, setValue] = useState('');
const [value, setValue] = useState("");

const { getItem, setItem, removeItem } = useLocalStorage('value');
const { getItem, setItem, removeItem } = useLocalStorage();

return (
<div className='tutorial-shorts'>
<h1 className='mb-2 text-3xl font-bold'>useLocalStorage</h1>
<div className="tutorial-shorts">
<h1 className="mb-2 text-3xl font-bold">useLocalStorage</h1>
<input
className='mb-4'
type='text'
className="mb-4"
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<div className='flex flex-row gap-4'>
<button onClick={() => setItem(value)}>Set</button>
<button onClick={() => console.log(getItem())}>Get</button>
<button onClick={removeItem}>Remove</button>
<div className="flex flex-row gap-4">
<button onClick={() => setItem("myKey", value)}>Set</button>
<button onClick={() => console.log(getItem("myKey"))}>Get</button>
<button onClick={() => removeItem("myKey")}>Remove</button>
</div>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
export const useLocalStorage = (key: string) => {
const setItem = (value: unknown) => {
export const useLocalStorage = () => {
const setItem = (key: string, value: unknown) => {
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.log(error);
}
};

const getItem = () => {
const getItem = (key: string) => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : undefined;
Expand All @@ -16,7 +16,7 @@ export const useLocalStorage = (key: string) => {
}
};

const removeItem = () => {
const removeItem = (key: string) => {
try {
window.localStorage.removeItem(key);
} catch (error) {
Expand Down