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

98 lines
2.7 KiB
TypeScript
Raw Normal View History

2023-07-31 23:47:18 +03:00
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { ErrorInfo } from '../components/BackendError';
2023-08-10 13:53:19 +03:00
import { DataCallback, getProfile, patchPassword,patchProfile } from '../utils/backendAPI';
import { IUserProfile, IUserUpdateData, IUserUpdatePassword } from '../utils/models';
import { useAuth } from './AuthContext';
2023-07-31 23:47:18 +03:00
2023-08-10 13:53:19 +03:00
interface IUserProfileContext {
2023-07-31 23:47:18 +03:00
user: IUserProfile | undefined
loading: boolean
processing: boolean
error: ErrorInfo
setError: (error: ErrorInfo) => void
updateUser: (data: IUserUpdateData, callback?: DataCallback<IUserProfile>) => void
2023-08-10 13:53:19 +03:00
updatePassword: (data: IUserUpdatePassword, callback?: () => void) => void
2023-07-31 23:47:18 +03:00
}
2023-08-10 13:53:19 +03:00
const ProfileContext = createContext<IUserProfileContext | null>(null);
2023-07-31 23:47:18 +03:00
export const useUserProfile = () => {
const context = useContext(ProfileContext);
if (!context) {
throw new Error(
'useUserProfile has to be used within <UserProfileState.Provider>'
);
}
return context;
}
interface UserProfileStateProps {
children: React.ReactNode
}
export const UserProfileState = ({ children }: UserProfileStateProps) => {
const [user, setUser] = useState<IUserProfile | undefined>(undefined);
const [loading, setLoading] = useState(false);
const [processing, setProcessing] = useState(false);
const [error, setError] = useState<ErrorInfo>(undefined);
2023-08-10 13:53:19 +03:00
const auth = useAuth()
2023-07-31 23:47:18 +03:00
const reload = useCallback(
() => {
setError(undefined);
setUser(undefined);
getProfile({
showError: true,
setLoading: setLoading,
onError: error => { setError(error); },
onSuccess: newData => { setUser(newData); }
});
}, [setUser]
);
const updateUser = useCallback(
(data: IUserUpdateData, callback?: DataCallback<IUserProfile>) => {
setError(undefined);
patchProfile({
data: data,
showError: true,
setLoading: setProcessing,
onError: error => { setError(error); },
onSuccess: newData => {
setUser(newData);
if (callback) callback(newData);
}
});
}, [setUser]
);
2023-08-10 13:53:19 +03:00
const updatePassword = useCallback(
(data: IUserUpdatePassword, callback?: () => void) => {
setError(undefined);
patchPassword({
data: data,
showError: true,
setLoading: setProcessing,
onError: error => { setError(error); },
onSuccess: () => {
setUser(undefined);
auth.logout();
if (callback) callback();
}});
}, [setUser, auth]
);
2023-07-31 23:47:18 +03:00
useEffect(() => {
reload();
}, [reload]);
return (
<ProfileContext.Provider
2023-08-10 13:53:19 +03:00
value={{user, updateUser, updatePassword, error, loading, setError, processing}}
2023-07-31 23:47:18 +03:00
>
{children}
</ProfileContext.Provider>
);
};