Program Commit
This commit is contained in:
52
frontend/src/contexts/ThemeContext.js
Normal file
52
frontend/src/contexts/ThemeContext.js
Normal file
@@ -0,0 +1,52 @@
|
||||
import React, { createContext, useState, useMemo, useContext, useEffect } from 'react';
|
||||
import { ThemeProvider as MuiThemeProvider } from '@mui/material/styles';
|
||||
import { lightTheme, darkTheme, discordTheme } from '../themes';
|
||||
import { UserContext } from './UserContext';
|
||||
import axios from 'axios';
|
||||
|
||||
export const ThemeContext = createContext();
|
||||
|
||||
export const ThemeProvider = ({ children }) => {
|
||||
const { user } = useContext(UserContext);
|
||||
const [themeName, setThemeName] = useState(localStorage.getItem('themeName') || 'discord');
|
||||
|
||||
useEffect(() => {
|
||||
if (user && user.theme) {
|
||||
setThemeName(user.theme);
|
||||
} else {
|
||||
const storedTheme = localStorage.getItem('themeName');
|
||||
if (storedTheme) {
|
||||
setThemeName(storedTheme);
|
||||
} else {
|
||||
setThemeName('discord');
|
||||
}
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const theme = useMemo(() => {
|
||||
switch (themeName) {
|
||||
case 'dark':
|
||||
return darkTheme;
|
||||
case 'discord':
|
||||
return discordTheme;
|
||||
default:
|
||||
return lightTheme;
|
||||
}
|
||||
}, [themeName]);
|
||||
|
||||
const changeTheme = (name) => {
|
||||
if (user) {
|
||||
axios.post('http://localhost:3002/api/user/theme', { userId: user.id, theme: name });
|
||||
}
|
||||
localStorage.setItem('themeName', name);
|
||||
setThemeName(name);
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ themeName, changeTheme }}>
|
||||
<MuiThemeProvider theme={theme}>
|
||||
{children}
|
||||
</MuiThemeProvider>
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
};
|
||||
13
frontend/src/contexts/UserContext.js
Normal file
13
frontend/src/contexts/UserContext.js
Normal file
@@ -0,0 +1,13 @@
|
||||
import React, { createContext, useState } from 'react';
|
||||
|
||||
export const UserContext = createContext();
|
||||
|
||||
export const UserProvider = ({ children }) => {
|
||||
const [user, setUser] = useState(null);
|
||||
|
||||
return (
|
||||
<UserContext.Provider value={{ user, setUser }}>
|
||||
{children}
|
||||
</UserContext.Provider>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user