mirror of
https://github.com/remvze/moodist.git
synced 2025-12-17 00:44:14 +00:00
feat: add local storage support
This commit is contained in:
parent
85768d8bca
commit
856b3e668e
2 changed files with 43 additions and 9 deletions
|
|
@ -1,4 +1,5 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
import { useCallback, useEffect } from 'react';
|
||||
import { useLocalStorage } from '@/hooks/use-local-storage';
|
||||
|
||||
import { useSound } from '@/hooks/use-sound';
|
||||
import { usePlay } from '@/contexts/play';
|
||||
|
|
@ -13,16 +14,15 @@ interface SoundProps {
|
|||
|
||||
export function Sound({ label, src }: SoundProps) {
|
||||
const { isPlaying } = usePlay();
|
||||
const [isSelected, setIsSelected] = useState(false);
|
||||
const [volume, setVolume] = useState(0.5);
|
||||
const [isSelected, setIsSelected] = useLocalStorage(
|
||||
`${label}-is-selected`,
|
||||
false,
|
||||
);
|
||||
const [volume, setVolume] = useLocalStorage(`${label}-volume`, 0.5);
|
||||
|
||||
const sound = useSound(src, { loop: true, volume });
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSelected) {
|
||||
setVolume(0.5);
|
||||
}
|
||||
|
||||
if (isSelected && isPlaying) {
|
||||
sound?.play();
|
||||
} else {
|
||||
|
|
@ -30,11 +30,16 @@ export function Sound({ label, src }: SoundProps) {
|
|||
}
|
||||
}, [isSelected, sound, isPlaying]);
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
setIsSelected(prev => !prev);
|
||||
setVolume(0.5);
|
||||
}, [setIsSelected, setVolume]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(styles.sound, isSelected && styles.selected)}
|
||||
onClick={() => setIsSelected(prev => !prev)}
|
||||
onKeyDown={() => setIsSelected(prev => !prev)}
|
||||
onClick={toggle}
|
||||
onKeyDown={toggle}
|
||||
>
|
||||
<h3 id={label}>{label}</h3>
|
||||
<input
|
||||
|
|
|
|||
29
src/hooks/use-local-storage.ts
Normal file
29
src/hooks/use-local-storage.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { type Dispatch, type SetStateAction, useEffect, useState } from 'react';
|
||||
|
||||
type SetValue<T> = Dispatch<SetStateAction<T>>;
|
||||
|
||||
export function useLocalStorage<T>(key: string, fallback: T): [T, SetValue<T>] {
|
||||
const [value, setValue] = useState(fallback);
|
||||
|
||||
useEffect(() => {
|
||||
const value = localStorage.getItem(key);
|
||||
|
||||
if (!value) return;
|
||||
|
||||
let parsed;
|
||||
|
||||
try {
|
||||
parsed = JSON.parse(value);
|
||||
} catch (error) {
|
||||
parsed = fallback;
|
||||
}
|
||||
|
||||
setValue(parsed);
|
||||
}, [key, fallback]);
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
}, [value, key]);
|
||||
|
||||
return [value, setValue];
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue