Skip to content

Commit

Permalink
fix: settings
Browse files Browse the repository at this point in the history
  • Loading branch information
baynt1 committed Sep 26, 2024
1 parent 16da358 commit 9051016
Show file tree
Hide file tree
Showing 7 changed files with 76 additions and 30 deletions.
29 changes: 27 additions & 2 deletions src/app/routes/router.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,38 @@
import { useNotify } from 'app/providers/app'
import { ErrorPage } from 'pages/error'
import { Settings } from 'pages/settings'
import React, { lazy } from 'react'
import React, { lazy, useEffect } from 'react'
import { useCookies } from 'react-cookie'
import { Route, Routes } from 'react-router'
import { getAxiosInstance } from 'shared/api/api-query/api-query'
import { setRoleState } from 'shared/redux/settings/settings-slice'
import { useAppDispatch, useAppSelector } from 'shared/redux/store'
import { PreloaderPage } from 'shared/ui/preloader-page'

const Router = () => {
const Main = lazy(async () => await import('pages/main'))
const Dashboard = lazy(async () => await import('pages/dashboard'))

const dispatch = useAppDispatch()
const { openNotification } = useNotify()
const [{ token }] = useCookies(['token'])
const access = useAppSelector((state) => state.settings.role)

const fetchData = async () => {
try {
const axiosInstance = await getAxiosInstance()
const res = await axiosInstance.get('/auth/me')
dispatch(setRoleState(res.data.role || ''))
} catch (error) {
dispatch(setRoleState(''))
openNotification('Произошла ошибка при загрузке данных о пользователе')
}
}

useEffect(() => {
if (token) fetchData()
}, [token])

return (
<Routes>
<Route path={'*'} element={<ErrorPage />} />
Expand All @@ -20,7 +45,7 @@ const Router = () => {
}
>
<Route path={'/'} element={<Dashboard />} />
<Route path={'settings'} element={<Settings />} />
{access === 'ADMINISTRATOR' && <Route path={'settings'} element={<Settings />} />}
</Route>
</Routes>
)
Expand Down
4 changes: 4 additions & 0 deletions src/features/auth/auth-form/auth-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@ import React, { FC } from 'react'
import { useCookies } from 'react-cookie'
import { getAxiosInstance } from 'shared/api/api-query/api-query'
import { useToggle } from 'shared/lib/hooks/use-toggle'
import { setRoleState } from 'shared/redux/settings/settings-slice'
import { useAppDispatch } from 'shared/redux/store'

export const AuthForm: FC = () => {
const [auth, handleAuth] = useToggle()
const { openNotification } = useNotify()
const dispatch = useAppDispatch()
const [_, updateToken] = useCookies(['token'])

const onFinish: FormProps<IMainFields>['onFinish'] = async (data) => {
Expand All @@ -34,6 +37,7 @@ export const AuthForm: FC = () => {

await axiosInstance.post('/auth/login', data).then((res) => {
updateToken('token', res.data.token)
dispatch(setRoleState('refetch'))
})
} catch (error) {
openNotification('Что-то пошло не так')
Expand Down
43 changes: 23 additions & 20 deletions src/features/settings/new-post/new-post.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,39 +62,42 @@ export const NewPost: FC<INewPostProps> = ({ open, handeOpen, item, refetch }) =
setLoading(true)
try {
const axiosInstance = await getAxiosInstance()

if (item && item.id) {
const users = data.users
? data.users.map((user) => {
return {
post: item.id,
user: user,
}
})
? data.users.map((user) => ({
post: item.id,
user: user,
}))
: []
await axiosInstance.patch(`/posts/${item.id}`, data).then(() => {
openNotification('Пост изменен', 'success')
handeOpen()
refetch()
setLoading(false)
})
await axiosInstance.post('/posts-users-access', users)
await axiosInstance.patch(`/posts/${item.id}`, data)
openNotification('Пост изменен', 'success')
handeOpen()
refetch()
await axiosInstance.patch(`/posts-users-access/post/${item.id}`, users)
} else {
await axiosInstance.post('/posts', data).then(() => {
openNotification('Пост создан', 'success')
handeOpen()
refetch()
setLoading(false)
const res = await axiosInstance.post('/posts', data)
await axiosInstance.patch(`/posts-users-access/post/${res.data.id}`, {
users: data.users,
})
openNotification('Пост создан', 'success')
handeOpen()
refetch()
}
} catch (error) {
openNotification('Что-то пошло не так')
openNotification('Что-то пошло не так', 'error')
} finally {
setLoading(false)
}
}

return (
<>
<Drawer title='Создание нового поста' onClose={handeOpen} open={open}>
<Drawer
title={item ? 'Изменение поста' : 'Создание нового поста'}
onClose={handeOpen}
open={open}
>
<Form
form={form}
onFinish={onFinish}
Expand Down
6 changes: 5 additions & 1 deletion src/features/settings/new-user/new-user.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,11 @@ export const NewUser: FC<INewUserProps> = ({ open, handleModal, item, refetch })
}, [item, open])

return (
<Drawer title='Создание нового пользователя' onClose={handleModal} open={open}>
<Drawer
title={item ? 'Изменение пользователя' : 'Создание нового пользователя'}
onClose={handleModal}
open={open}
>
<Form
form={form}
onFinish={onFinish}
Expand Down
1 change: 1 addition & 0 deletions src/shared/api/api-query/api-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const createAxiosInstance = async () => {
(error) => {
if (error.response && error.response.status === 401) {
Cookies.remove('token')
window.location.replace('/')
}
return Promise.reject(error)
},
Expand Down
6 changes: 5 additions & 1 deletion src/shared/redux/settings/settings-slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createSlice } from '@reduxjs/toolkit'
const initialState = {
posts: [],
users: [],
role: '',
}

export const SettingsSlice = createSlice({
Expand All @@ -15,9 +16,12 @@ export const SettingsSlice = createSlice({
setUsersState: (state, action) => {
state.users = action.payload
},
setRoleState: (state, action) => {
state.role = action.payload
},
},
})

export const { setPostsState, setUsersState } = SettingsSlice.actions
export const { setPostsState, setUsersState, setRoleState } = SettingsSlice.actions

export default SettingsSlice.reducer
17 changes: 11 additions & 6 deletions src/widget/header/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import { FC } from 'react'
import { useCookies } from 'react-cookie'
import { useMediaQuery } from 'react-responsive'
import { useNavigate } from 'react-router'
import { useAppSelector } from 'shared/redux/store'

export const Header: FC = () => {
const navigator = useNavigate()
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [token, update, removeToken] = useCookies(['token'])
const isMobile = useMediaQuery({ query: '(max-width: 768px )' })
const access = useAppSelector((state) => state.settings.role)

return (
<Flex
Expand Down Expand Up @@ -41,12 +43,15 @@ export const Header: FC = () => {
<Space style={{ cursor: 'pointer', color: '#eeeeee' }} onClick={() => navigator('/')}>
Аналитика
</Space>
<Space
style={{ cursor: 'pointer', color: '#eeeeee' }}
onClick={() => navigator('/settings')}
>
Настройки
</Space>

{access === 'ADMINISTRATOR' && (
<Space
style={{ cursor: 'pointer', color: '#eeeeee' }}
onClick={() => navigator('/settings')}
>
Настройки
</Space>
)}
<Space style={{ cursor: 'pointer', color: '#eeeeee' }} onClick={() => removeToken('token')}>
Выйти
</Space>
Expand Down

0 comments on commit 9051016

Please sign in to comment.