Skip to content

Commit

Permalink
feat: add initAuthData request, fix themes
Browse files Browse the repository at this point in the history
  • Loading branch information
TomatoVan committed Apr 9, 2024
1 parent 6cb799b commit f55772d
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 22 deletions.
2 changes: 1 addition & 1 deletion json-server/db.json
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,7 @@
},
"avatar": "https://mobimg.b-cdn.net/v3/fetch/22/2207633df03a819cd72889249c8361a8.jpeg?w=1470&r=0.5625",
"jsonSettings": {
"theme": "app_orange_theme",
"theme": "app_light_theme",
"isFirstVisit": true,
"settingsPageHasBeenOpen": false
}
Expand Down
14 changes: 10 additions & 4 deletions src/app/App.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
import React, { Suspense, useEffect } from 'react';
import './styles/index.scss';
import { useDispatch, useSelector } from 'react-redux';
import { useSelector } from 'react-redux';
import { classNames } from '@/shared/lib/classNames/classNames';
import { AppRouter } from './providers/router';
import { Navbar } from '@/widgets/Navbar';
import { Sidebar } from '@/widgets/Sidebar';
import { getUserInited, userActions } from '@/entities/User';
import { getUserInited, initAuthData } from '@/entities/User';
import { useTheme } from '@/shared/lib/hook/useTheme/useTheme';
import { useAppDispatch } from '@/shared/lib/hook/useAppDispatch/useAppDispatch';
import { PageLoader } from '@/features/PageLoader';

function App() {
const { theme } = useTheme();
const dispatch = useDispatch();
const dispatch = useAppDispatch();
const inited = useSelector(getUserInited);

useEffect(() => {
dispatch(userActions.initAuthData());
dispatch(initAuthData());
}, [dispatch]);

if (!inited) {
return <PageLoader />;
}

return (
<div className={classNames('app', {}, [theme])}>
<Suspense fallback="">
Expand Down
8 changes: 5 additions & 3 deletions src/app/providers/ThemeProvider/ui/ThemeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ interface ThemeProviderProps {
const ThemeProvider = (props: ThemeProviderProps) => {
const { initialTheme, children } = props;

const { theme: defaultTheme = Theme.LIGHT } = useJsonSettings();
const { theme: defaultTheme } = useJsonSettings();
const [isThemeInited, setIsThemeInited] = useState(false);

const [theme, setTheme] = useState<Theme>(initialTheme || defaultTheme);
const [theme, setTheme] = useState<Theme>(
initialTheme || defaultTheme || Theme.LIGHT,
);

useEffect(() => {
if (!isThemeInited) {
if (!isThemeInited && defaultTheme) {
setTheme(defaultTheme);
setIsThemeInited(true);
}
Expand Down
8 changes: 8 additions & 0 deletions src/entities/User/api/userApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,16 @@ const userApi = rtkApi.injectEndpoints({
},
}),
}),
getUserDataById: build.query<User, string>({
query: (userId) => ({
url: `/users/${userId}`,
method: 'GET',
}),
}),
}),
});

export const setJsonSettingsMutation =
userApi.endpoints.setJsonSettings.initiate;

export const getUserDataByIdQuery = userApi.endpoints.getUserDataById.initiate;
1 change: 1 addition & 0 deletions src/entities/User/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export {
export { UserRole } from './model/consts/consts';
export { useJsonSettings } from './model/selectors/jsonSettings';
export { saveJsonSettings } from './model/services/saveJsonSettings';
export { initAuthData } from './model/services/initAuthData';
28 changes: 28 additions & 0 deletions src/entities/User/model/services/initAuthData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { createAsyncThunk } from '@reduxjs/toolkit';
import { ThunkConfig } from '@/app/providers/StoreProvider';
import { getUserDataByIdQuery } from '../../api/userApi';
import { User } from '../types/user';
import { USER_LOCALSTORAGE_KEY } from '@/shared/const/localstorage';

export const initAuthData = createAsyncThunk<User, void, ThunkConfig<string>>(
'user/initAuthData',
async (_, thunkApi) => {
const { rejectWithValue, dispatch } = thunkApi;

const userId = localStorage.getItem(USER_LOCALSTORAGE_KEY);
if (!userId) {
return rejectWithValue('');
}

try {
const response = await dispatch(
getUserDataByIdQuery(userId),
).unwrap();

return response;
} catch (e) {
console.log(e);
return rejectWithValue('');
}
},
);
24 changes: 15 additions & 9 deletions src/entities/User/model/slice/userSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { User, UserSchema } from '../types/user';
import { setFeatureFlags } from '@/shared/lib/features';
import { saveJsonSettings } from '../services/saveJsonSettings';
import { JsonSettings } from '../types/jsonSettings';
import { initAuthData } from '../services/initAuthData';

const initialState: UserSchema = {
_inited: false,
Expand All @@ -16,15 +17,7 @@ export const userSlice = createSlice({
setAuthData: (state, action: PayloadAction<User>) => {
state.authData = action.payload;
setFeatureFlags(action.payload.features);
},
initAuthData: (state) => {
const user = localStorage.getItem(USER_LOCALSTORAGE_KEY);
if (user) {
const json = JSON.parse(user) as User;
state.authData = json;
setFeatureFlags(json.features);
}
state._inited = true;
localStorage.setItem(USER_LOCALSTORAGE_KEY, action.payload.id);
},
logout: (state) => {
state.authData = undefined;
Expand All @@ -40,6 +33,19 @@ export const userSlice = createSlice({
}
},
);
builder.addCase(
initAuthData.fulfilled,
(state, { payload }: PayloadAction<User>) => {
state.authData = payload;
setFeatureFlags(payload.features);
state._inited = true;
},
);
builder.addCase(initAuthData.rejected, (state) => {
if (state.authData) {
state._inited = true;
}
});
},
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { createAsyncThunk } from '@reduxjs/toolkit';
import { USER_LOCALSTORAGE_KEY } from '@/shared/const/localstorage';
import { ThunkConfig } from '@/app/providers/StoreProvider';
import { User, userActions } from '../../../../../entities/User';

Expand All @@ -20,10 +19,6 @@ export const loginByUsername = createAsyncThunk<
if (!response.data) {
throw new Error();
}
localStorage.setItem(
USER_LOCALSTORAGE_KEY,
JSON.stringify(response.data),
);

dispatch(userActions.setAuthData(response.data));

Expand Down

0 comments on commit f55772d

Please sign in to comment.