feat: initialise template
This commit is contained in:
69
src/lib/utils/auth/hooks/useUpdateCurrentUser.ts
Normal file
69
src/lib/utils/auth/hooks/useUpdateCurrentUser.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import {
|
||||
ApiError,
|
||||
APIResponse,
|
||||
apiClient,
|
||||
isApiResponse,
|
||||
isApiError,
|
||||
} from '..';
|
||||
|
||||
export interface UpdateUserRequest {
|
||||
nickname: string;
|
||||
code?: string;
|
||||
email?: string;
|
||||
old_password?: string;
|
||||
password?: string;
|
||||
}
|
||||
|
||||
interface UseUpdateCurrentUser {
|
||||
isLoading: boolean;
|
||||
error: ApiError | null;
|
||||
data: APIResponse | null;
|
||||
updateCurrentUser: (payload: UpdateUserRequest) => Promise<void>;
|
||||
}
|
||||
|
||||
export const useUpdateCurrentUser = (): UseUpdateCurrentUser => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<ApiError | null>(null);
|
||||
const [data, setData] = useState<APIResponse | null>(null);
|
||||
|
||||
const updateCurrentUser = useCallback(
|
||||
(payload: UpdateUserRequest): Promise<void> => {
|
||||
if (payload.email && !payload.code) {
|
||||
setError({
|
||||
message: 'Verification code is required when updating email.',
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (payload.password && !payload.old_password) {
|
||||
setError({
|
||||
message: 'Old password is required when updating password.',
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
setData(null);
|
||||
|
||||
const url = 'v1/user/me';
|
||||
|
||||
return apiClient()
|
||||
.patch(url, payload)
|
||||
.then(res => {
|
||||
if (isApiResponse(res)) {
|
||||
setData(res);
|
||||
} else if (isApiError(res)) {
|
||||
setError(res);
|
||||
} else {
|
||||
setError({ message: 'Received unknown response structure.' });
|
||||
}
|
||||
})
|
||||
.catch(() => setError({ message: 'Network or unexpected error' }))
|
||||
.finally(() => setIsLoading(false));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return { isLoading, error, data, updateCurrentUser };
|
||||
};
|
||||
Reference in New Issue
Block a user