1
0
Fork 0
mirror of https://github.com/pawelmalak/flame.git synced 2025-07-19 11:39:36 +02:00
flame/client/src/store/action-creators/theme.ts

74 lines
1.8 KiB
TypeScript
Raw Normal View History

import { Dispatch } from 'redux';
2022-03-24 16:07:14 +01:00
import {
AddThemeAction,
FetchThemesAction,
SetThemeAction,
} from '../actions/theme';
import { ActionType } from '../action-types';
import { Theme, ApiResponse, ThemeColors } from '../../interfaces';
2022-03-24 16:07:14 +01:00
import { applyAuth, parseThemeToPAB } from '../../utility';
import axios, { AxiosError } from 'axios';
export const setTheme =
(colors: ThemeColors, remeberTheme: boolean = true) =>
(dispatch: Dispatch<SetThemeAction>) => {
if (remeberTheme) {
localStorage.setItem('theme', parseThemeToPAB(colors));
}
for (const [key, value] of Object.entries(colors)) {
document.body.style.setProperty(`--color-${key}`, value);
}
dispatch({
type: ActionType.setTheme,
payload: colors,
});
};
export const fetchThemes =
() => async (dispatch: Dispatch<FetchThemesAction>) => {
try {
const res = await axios.get<ApiResponse<Theme[]>>('/api/themes');
dispatch({
type: ActionType.fetchThemes,
payload: res.data.data,
});
} catch (err) {
console.log(err);
}
};
2022-03-24 16:07:14 +01:00
export const addTheme =
(theme: Theme) => async (dispatch: Dispatch<AddThemeAction>) => {
try {
const res = await axios.post<ApiResponse<Theme>>('/api/themes', theme, {
headers: applyAuth(),
});
2022-03-24 16:07:14 +01:00
dispatch({
type: ActionType.addTheme,
payload: res.data.data,
});
2022-03-24 16:07:14 +01:00
dispatch<any>({
type: ActionType.createNotification,
payload: {
title: 'Success',
message: 'Theme added',
},
});
} catch (err) {
const error = err as AxiosError<{ error: string }>;
2022-03-24 16:07:14 +01:00
dispatch<any>({
type: ActionType.createNotification,
payload: {
title: 'Error',
message: error.response?.data.error,
},
});
}
};