feat: V2 with TypeScript

This commit is contained in:
Ben Elferink
2024-12-14 16:14:14 +02:00
parent f6c0a52ab5
commit a41cab872f
63 changed files with 13390 additions and 35925 deletions

View File

@@ -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]
}

View 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

View File

@@ -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