ConceptPortal-public/rsconcept/frontend/src/context/UsersContext.tsx

73 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-07-25 20:27:29 +03:00
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
2023-07-15 17:46:19 +03:00
2023-07-25 20:27:29 +03:00
import { getActiveUsers } from '../utils/backendAPI';
import { type IUserInfo } from '../utils/models';
2023-07-15 17:46:19 +03:00
interface IUsersContext {
users: IUserInfo[]
reload: () => void
getUserLabel: (userID: number | null) => string
2023-07-15 17:46:19 +03:00
}
2023-07-25 20:27:29 +03:00
const UsersContext = createContext<IUsersContext | null>(null)
export const useUsers = (): IUsersContext => {
const context = useContext(UsersContext);
2023-07-25 20:27:29 +03:00
if (context == null) {
throw new Error(
'useUsers has to be used within <UsersState.Provider>'
);
}
return context;
}
2023-07-15 17:46:19 +03:00
interface UsersStateProps {
children: React.ReactNode
}
export const UsersState = ({ children }: UsersStateProps) => {
2023-07-25 20:27:29 +03:00
const [users, setUsers] = useState<IUserInfo[]>([])
2023-07-15 17:46:19 +03:00
const getUserLabel = (userID: number | null) => {
2023-07-25 20:27:29 +03:00
const user = users.find(({ id }) => id === userID)
if (!user) {
2023-07-26 10:59:55 +03:00
return (userID ? userID.toString() : 'Отсутствует');
2023-07-15 17:46:19 +03:00
}
const hasFirstName = user.first_name !== '';
const hasLastName = user.last_name !== '';
2023-07-25 20:27:29 +03:00
if (hasFirstName || hasLastName) {
if (!hasLastName) {
2023-07-15 17:46:19 +03:00
return user.first_name;
}
2023-07-25 20:27:29 +03:00
if (!hasFirstName) {
2023-07-15 17:46:19 +03:00
return user.last_name;
}
2023-07-25 20:27:29 +03:00
return user.first_name + ' ' + user.last_name;
2023-07-15 17:46:19 +03:00
}
return user.username;
2023-07-25 20:27:29 +03:00
}
2023-07-15 17:46:19 +03:00
const reload = useCallback(
() => {
getActiveUsers({
showError: true,
2023-07-25 20:27:29 +03:00
onError: () => { setUsers([]); },
onSuccess: newData => { setUsers(newData); }
2023-07-15 17:46:19 +03:00
});
}, [setUsers]
2023-07-25 20:27:29 +03:00
)
2023-07-15 17:46:19 +03:00
useEffect(() => {
reload();
2023-07-25 20:27:29 +03:00
}, [reload])
2023-07-15 17:46:19 +03:00
return (
<UsersContext.Provider value={{
users,
2023-07-25 20:27:29 +03:00
reload,
getUserLabel
2023-07-15 17:46:19 +03:00
}}>
{ children }
</UsersContext.Provider>
2023-07-25 20:27:29 +03:00
);
}