Skip to content

Commit

Permalink
Rtk query avatar endpoint (#783)
Browse files Browse the repository at this point in the history
* add option to pass headers to query endpoint

* implement call to update avatar from AvatarForm through RTK query which automates the process of invalidating the cache and refretching the profile/avatar in other components
  • Loading branch information
dpgraham4401 authored Sep 1, 2024
1 parent b14030b commit d2ccfaf
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 14 deletions.
27 changes: 16 additions & 11 deletions client/app/features/profile/components/AvatarForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useForm } from 'react-hook-form';
import { FaUser } from 'react-icons/fa';
import { Avatar, AvatarFallback, AvatarImage, Input } from '~/components/ui';
import { useAuth } from '~/hooks';
import { htApi } from '~/services';
import { useUpdateAvatarMutation } from '~/store';

interface AvatarFormProps {
avatar?: string;
Expand All @@ -14,30 +14,35 @@ export function AvatarForm({ avatar }: AvatarFormProps) {
const [preview, setPreview] = useState<string | undefined>(avatar);
const inputRef = useRef<HTMLInputElement | null>(null);
const { register, handleSubmit, watch } = useForm({ mode: 'onChange' });
const [updateAvatar, { data, isSuccess }] = useUpdateAvatarMutation();
const { user } = useAuth();

const onSubmit = (data: any) => {
const formData = new FormData();
formData.append('avatar', data.avatar[0]);
htApi
.patch(`/profile/${user?.id}`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then((res) => setPreview(res.data.avatar))
.catch((err) => console.log(err));
if (user?.id) {
updateAvatar({ id: user?.id, avatar: formData });
}
};

const registerProps = register('avatar', {
required: true,
});

// When the avatar is changed, submit the form
useEffect(() => {
watch((data) => {
onSubmit(data);
});
}, [watch]);

useEffect(() => {
if (isSuccess) {
setPreview(data?.avatar);
}
}, [isSuccess, data]);

// create the props for the avatar input
const registerProps = register('avatar', {
required: true,
});

return (
<form onSubmit={handleSubmit(onSubmit)}>
<Input
Expand Down
5 changes: 3 additions & 2 deletions client/app/store/htApi.slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export interface HtApiQueryArgs {
method: AxiosRequestConfig['method'];
data?: AxiosRequestConfig['data'];
params?: AxiosRequestConfig['params'];
headers?: AxiosRequestConfig['headers'];
}

export interface HtApiError extends AxiosError {
Expand All @@ -42,8 +43,8 @@ export const htApiBaseQuery =
HtApiError
// Meta
> =>
async ({ url, method, data, params }) => {
return htApi({ url: baseUrl + url, method, data, params })
async ({ url, method, data, params, headers }) => {
return htApi({ url: baseUrl + url, method, data, params, headers })
.then((response) => {
return { data: response.data };
})
Expand Down
2 changes: 1 addition & 1 deletion client/app/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ export const {
useLogoutMutation,
useGetUserQuery,
useGetProfileQuery,
useUpdateProfileMutation,
useGetRcrainfoProfileQuery,
useUpdateUserMutation,
useUpdateRcrainfoProfileMutation,
useSyncRcrainfoProfileMutation,
useUpdateAvatarMutation,
} = userApi;

// Authentication Slice
Expand Down
11 changes: 11 additions & 0 deletions client/app/store/userApi/userApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,17 @@ export const userApi = haztrakApi.injectEndpoints({
}),
invalidatesTags: ['profile'],
}),
updateAvatar: build.mutation<{ avatar: string }, { id: string; avatar: FormData }>({
query: ({ id, avatar }) => ({
url: `profile/${id}`,
method: 'PATCH',
data: avatar,
headers: {
'Content-Type': 'multipart/form-data',
},
}),
invalidatesTags: ['profile'],
}),
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
getProfile: build.query<ProfileSlice, void>({
query: () => ({
Expand Down

0 comments on commit d2ccfaf

Please sign in to comment.