2020-09-20 10:33:39 +02:00
|
|
|
import { useDispatch, useSelector } from 'react-redux';
|
|
|
|
import { setTheme } from 'redux/actions/app';
|
|
|
|
import { getItem, setItem } from 'lib/web';
|
|
|
|
import { THEME_CONFIG } from 'lib/constants';
|
|
|
|
import { useEffect } from 'react';
|
|
|
|
|
2020-10-01 01:27:27 +02:00
|
|
|
export default function useTheme() {
|
2021-04-28 11:12:17 +02:00
|
|
|
const defaultTheme =
|
2021-04-28 11:18:54 +02:00
|
|
|
typeof window !== 'undefined'
|
2021-09-21 13:28:36 +02:00
|
|
|
? window?.matchMedia('(prefers-color-scheme: dark)')?.matches
|
2021-04-28 11:12:17 +02:00
|
|
|
? 'dark'
|
|
|
|
: 'light'
|
|
|
|
: 'light';
|
2021-04-26 09:06:08 +02:00
|
|
|
const theme = useSelector(state => state.app.theme || getItem(THEME_CONFIG) || defaultTheme);
|
2020-09-20 10:33:39 +02:00
|
|
|
const dispatch = useDispatch();
|
|
|
|
|
|
|
|
function saveTheme(value) {
|
|
|
|
setItem(THEME_CONFIG, value);
|
|
|
|
dispatch(setTheme(value));
|
|
|
|
}
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
document.body.setAttribute('data-theme', theme);
|
|
|
|
}, [theme]);
|
|
|
|
|
|
|
|
return [theme, saveTheme];
|
|
|
|
}
|