feat: V2 with TypeScript
This commit is contained in:
@@ -1,20 +0,0 @@
|
||||
import {useState, useEffect} from 'react'
|
||||
|
||||
/* How to use this hook:
|
||||
import useLocalStorage from './hooks/useLocalStorage';
|
||||
|
||||
function App() {
|
||||
const [example, setExample] = useLocalStorage('example_key', {example: 'anything as default'});
|
||||
|
||||
return ();
|
||||
}; */
|
||||
|
||||
export default function useLocalStorage(key = '', defaultValue = null) {
|
||||
const [value, setValue] = useState(JSON.parse(localStorage.getItem(key)) || defaultValue)
|
||||
|
||||
useEffect(() => {
|
||||
if (value != null) localStorage.setItem(key, JSON.stringify(value))
|
||||
}, [key, value])
|
||||
|
||||
return [value, setValue]
|
||||
}
|
||||
42
client/src/hooks/useLocalStorage.ts
Normal file
42
client/src/hooks/useLocalStorage.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
/*
|
||||
|
||||
How to use this hook:
|
||||
import useLocalStorage from './hooks/useLocalStorage';
|
||||
|
||||
function App() {
|
||||
const [example, setExample] = useLocalStorage('example_key', { example: 'anything as default' });
|
||||
|
||||
return ();
|
||||
};
|
||||
|
||||
*/
|
||||
|
||||
const getLsVal = (key: string, defaultValue: any) => {
|
||||
const storedStr = localStorage.getItem(key) || ''
|
||||
|
||||
if (!!storedStr) {
|
||||
return JSON.parse(storedStr)
|
||||
} else {
|
||||
return defaultValue
|
||||
}
|
||||
}
|
||||
|
||||
const setLsVal = (key: string, value: any) => {
|
||||
if (value !== undefined && value !== null) {
|
||||
const str = JSON.stringify(value)
|
||||
|
||||
localStorage.setItem(key, str)
|
||||
}
|
||||
}
|
||||
|
||||
const useLocalStorage = (key: string, defaultValue: any = null) => {
|
||||
const [value, setValue] = useState(getLsVal(key, defaultValue))
|
||||
|
||||
useEffect(() => setLsVal(key, value), [key, value])
|
||||
|
||||
return [value, setValue]
|
||||
}
|
||||
|
||||
export default useLocalStorage
|
||||
@@ -1,15 +1,19 @@
|
||||
import {useState, useEffect} from 'react'
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
/* How to use this hook:
|
||||
/*
|
||||
|
||||
How to use this hook:
|
||||
import useMediaQuery from './hooks/useMediaQuery';
|
||||
|
||||
function App() {
|
||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||
|
||||
return ();
|
||||
}; */
|
||||
};
|
||||
|
||||
export default function useMediaQuery(query = '(max-width: 768px)') {
|
||||
*/
|
||||
|
||||
const useMediaQuery = (query: string = '(max-width: 768px)') => {
|
||||
const [matches, setMatches] = useState(window.matchMedia(query).matches)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -22,3 +26,5 @@ export default function useMediaQuery(query = '(max-width: 768px)') {
|
||||
|
||||
return matches
|
||||
}
|
||||
|
||||
export default useMediaQuery
|
||||
Reference in New Issue
Block a user