Skip to content

Commit

Permalink
fix: fetch user with clerkId
Browse files Browse the repository at this point in the history
  • Loading branch information
hyochan committed Nov 5, 2024
1 parent e26a7f2 commit 208c54b
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 40 deletions.
24 changes: 14 additions & 10 deletions app/(home)/onboarding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,28 +79,32 @@ type FormData = yup.InferType<
}
>;

const fetcher = async (authId: string | null, supabase: SupabaseClient) => {
if (!authId) return;
const fetcher = async (
clerkId: string | null | undefined,
supabase: SupabaseClient,
) => {
if (!clerkId) return;

const {profile, userTags} = await fetchUserProfile({
authId,
clerkId,
supabase,
});

return {profile, userTags};
};

export default function Onboarding(): JSX.Element {
const {theme} = useDooboo();
const [displayNameError, setDisplayNameError] = useState<string>();
const [{authId, user}, setAuth] = useRecoilState(authRecoilState);
const [{user}, setAuth] = useRecoilState(authRecoilState);
const [tag, setTag] = useState('');
const [tags, setTags] = useState<string[]>([]);
const [profileImg, setProfileImg] = useState<string>();
const {supabase} = useSupabase();
const {signOut, isSignedIn} = useAuth();
const {signOut, isSignedIn, userId} = useAuth();

const {data, error} = useSwr(authId && `/profile/${authId}`, () =>
fetcher(authId, supabase!),
const {data, error} = useSwr(userId && `/profile/${userId}`, () =>
fetcher(userId, supabase!),
);

const handleAddTag = () => {
Expand Down Expand Up @@ -131,12 +135,12 @@ export default function Onboarding(): JSX.Element {
});

const handleFinishOnboarding: SubmitHandler<FormData> = async (data) => {
if (!authId || !supabase) return;
if (!userId || !supabase) return;

let image: ImageInsertArgs | undefined = {};

if (profileImg && !profileImg.startsWith('http')) {
const destPath = `users/${authId}`;
const destPath = `users/${userId}`;

image = await uploadFileToSupabase({
uri: profileImg,
Expand All @@ -155,7 +159,7 @@ export default function Onboarding(): JSX.Element {
try {
const updatedUser = await fetchUpdateProfile({
args: formDataWithTags,
authId,
clerkId: userId,
tags: tags || [],
supabase,
});
Expand Down
24 changes: 13 additions & 11 deletions app/(home)/settings/profile-update.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
import {useState, useEffect} from 'react';
import useSwr from 'swr';
import {t} from '../../../src/STRINGS';
import {useRecoilState} from 'recoil';
import {useSetRecoilState} from 'recoil';
import {authRecoilState} from '../../../src/recoil/atoms';
import {uploadFileToSupabase} from '../../../src/supabase';
import {ImageInsertArgs} from '../../../src/types';
Expand All @@ -32,6 +32,7 @@ import {showAlert} from '../../../src/utils/alert';
import {RectButton} from 'react-native-gesture-handler';
import ErrorBoundary from 'react-native-error-boundary';
import useSupabase, {SupabaseClient} from '../../../src/hooks/useSupabase';
import {useAuth} from '@clerk/clerk-expo';

const Container = styled.SafeAreaView`
flex: 1;
Expand Down Expand Up @@ -72,16 +73,16 @@ type FormData = yup.InferType<
>;

const fetcher = async ({
authId,
clerkId,
supabase,
}: {
authId?: string | null;
clerkId?: string | null;
supabase: SupabaseClient;
}) => {
if (!authId || !supabase) return;
if (!clerkId || !supabase) return;

const {profile, userTags} = await fetchUserProfile({
authId,
clerkId,
supabase,
});

Expand All @@ -90,16 +91,17 @@ const fetcher = async ({

export default function ProfileUpdate(): JSX.Element {
const {theme} = useDooboo();
const [{authId}, setAuth] = useRecoilState(authRecoilState);
const setAuth = useSetRecoilState(authRecoilState);
const {userId} = useAuth();
const [tag, setTag] = useState('');
const [tags, setTags] = useState<string[]>([]);
const [profileImg, setProfileImg] = useState<string>();
const [displayNameError, setDisplayNameError] = useState<string>();
const {supabase} = useSupabase();
const {back} = useRouter();

const {data: user, error} = useSwr(authId && `/profile/${authId}`, () =>
fetcher({supabase: supabase!, authId}),
const {data: user, error} = useSwr(userId && `/profile/${userId}`, () =>
fetcher({supabase: supabase!, clerkId: userId}),
);

const handleAddTag = () => {
Expand All @@ -119,12 +121,12 @@ export default function ProfileUpdate(): JSX.Element {
});

const handleProfileUpdate: SubmitHandler<FormData> = async (data) => {
if (!authId || !supabase) return;
if (!userId || !supabase) return;

let image: ImageInsertArgs | undefined = {};

if (profileImg && !profileImg.startsWith('http')) {
const destPath = `users/${authId}`;
const destPath = `users/${userId}`;

image = await uploadFileToSupabase({
supabase,
Expand All @@ -148,7 +150,7 @@ export default function ProfileUpdate(): JSX.Element {
try {
const user = await fetchUpdateProfile({
args: formDataWithTags,
authId,
clerkId: userId,
tags: tags || [],
supabase,
});
Expand Down
10 changes: 3 additions & 7 deletions app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,8 @@ function App(): JSX.Element | null {
}
}

if (!existingUser) {
return;
}

const {profile, userTags} = await fetchUserProfile({
authId: existingUser.id,
clerkId: user.id,
supabase,
});

Expand All @@ -158,12 +154,12 @@ function App(): JSX.Element | null {
}

const blockedUserIds = await fetchBlockUserIds({
userId: existingUser.id,
userId: user.id,
supabase,
});

setAuth({
authId: existingUser.id,
authId: profile.id,
user: profile,
blockedUserIds,
tags: userTags,
Expand Down
26 changes: 14 additions & 12 deletions src/apis/profileQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,30 @@ import {t} from '../STRINGS';
import {User, UserUpdateArgs} from '../types';

export const fetchUserProfile = async ({
authId,
clerkId,
supabase,
}: {
authId: string;
clerkId: string;
supabase: SupabaseClient;
}) => {
const {data: profile, error: profileError} = await supabase
.from('users')
.select('*')
.eq('id', authId)
.eq('clerk_id', clerkId)
.single();

if (profileError) {
if (profileError || !profile) {
if (__DEV__) {
console.error(profileError);
}

throw new Error(t('error.failedToFetchData'));
}

const {data: tagsData, error: tagsError} = await supabase
.from('_TagToUser')
.select('A')
.eq('B', authId);
.eq('B', profile.id);

if (tagsError) {
throw new Error(tagsError.message);
Expand Down Expand Up @@ -100,13 +102,13 @@ export const fetchUserWithDisplayName = async ({

export const fetchUpdateProfile = async ({
args,
authId,
clerkId,
tags,
supabase,
}: {
args: UserUpdateArgs;
tags: string[];
authId: string;
clerkId: string;
supabase: SupabaseClient;
}) => {
if (!args.display_name) {
Expand All @@ -119,7 +121,7 @@ export const fetchUpdateProfile = async ({
.from('users')
.select('id')
.eq('display_name', args.display_name)
.neq('id', authId)
.neq('clerk_id', clerkId)
.single();

// PGRST116 means no matching record found
Expand All @@ -130,7 +132,7 @@ export const fetchUpdateProfile = async ({
throw new Error(t('error.default'));
}

if (existingUser) {
if (!existingUser?.id) {
const error = new Error(t('error.displayNameExists'));
error.name = 'displayName';
throw error;
Expand All @@ -141,7 +143,7 @@ export const fetchUpdateProfile = async ({
.update({
...args,
})
.eq('id', authId)
.eq('id', existingUser.id)
.select('*')
.single();

Expand All @@ -158,15 +160,15 @@ export const fetchUpdateProfile = async ({
.from('tags')
.upsert({tag: tagData})
.eq('tag', tagData)
.eq('id', authId)
.eq('id', existingUser.id)
.select('id')
.single();

if (data?.id) {
await supabase.from('_TagToUser').upsert(
{
A: data.id,
B: authId,
B: existingUser.id,
},
{
ignoreDuplicates: true,
Expand Down

0 comments on commit 208c54b

Please sign in to comment.