Skip to content

Commit

Permalink
refactor: unify new supabase client in useSupabase
Browse files Browse the repository at this point in the history
  • Loading branch information
hyochan committed Sep 18, 2024
1 parent 1663180 commit 965665e
Show file tree
Hide file tree
Showing 25 changed files with 960 additions and 152 deletions.
8 changes: 5 additions & 3 deletions app/(home)/(tabs)/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from '../../../src/recoil/atoms';
import ListEmptyItem from '../../../src/components/uis/ListEmptyItem';
import ErrorBoundary from 'react-native-error-boundary';
import useSupabase from '../../../src/hooks/useSupabase';

const Container = styled.View`
flex: 1;
Expand All @@ -25,6 +26,7 @@ const Container = styled.View`
`;

export default function Posts(): JSX.Element {
const {supabase} = useSupabase();
const {push} = useRouter();
const {authId, blockedUserIds} = useRecoilValue(authRecoilState);
const [cursor, setCursor] = useState<string | undefined>(undefined);
Expand All @@ -34,13 +36,13 @@ export default function Posts(): JSX.Element {

const fetcher = useCallback(
(cursor: string | undefined) =>
fetchPostPagination({cursor, blockedUserIds}),
[blockedUserIds],
fetchPostPagination({cursor, blockedUserIds, supabase: supabase!}),
[blockedUserIds, supabase],
);

const {error, isValidating, mutate} = useSWR(
['posts', cursor],
() => fetchPostPagination({cursor, blockedUserIds}),
() => fetchPostPagination({cursor, blockedUserIds, supabase: supabase!}),
{
revalidateOnFocus: false,
revalidateIfStale: false,
Expand Down
15 changes: 11 additions & 4 deletions app/(home)/onboarding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import FallbackComponent from '../../src/components/uis/FallbackComponent';
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';

const Container = styled.SafeAreaView`
flex: 1;
Expand Down Expand Up @@ -76,10 +77,13 @@ type FormData = yup.InferType<
}
>;

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

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

Expand All @@ -90,9 +94,10 @@ export default function Onboarding(): JSX.Element {
const [tag, setTag] = useState('');
const [tags, setTags] = useState<string[]>([]);
const [profileImg, setProfileImg] = useState<string>();
const {supabase} = useSupabase();

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

const handleAddTag = () => {
Expand All @@ -112,7 +117,7 @@ export default function Onboarding(): JSX.Element {
});

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

let image: ImageInsertArgs | undefined = {};

Expand All @@ -124,6 +129,7 @@ export default function Onboarding(): JSX.Element {
fileType: 'Image',
bucket: 'images',
destPath,
supabase,
});
}

Expand All @@ -137,6 +143,7 @@ export default function Onboarding(): JSX.Element {
args: formDataWithTags,
authId,
tags: tags || [],
supabase,
});

if (updatedUser) {
Expand Down
11 changes: 7 additions & 4 deletions app/(home)/post/[id]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
import {RectButton} from 'react-native-gesture-handler';
import ErrorBoundary from 'react-native-error-boundary';
import FallbackComponent from '../../../../src/components/uis/FallbackComponent';
import useSupabase from '../../../../src/hooks/useSupabase';

const Container = styled.View`
background-color: ${({theme}) => theme.bg.basic};
Expand All @@ -44,6 +45,7 @@ const Content = styled.View`
`;

export default function PostDetails(): JSX.Element {
const {supabase} = useSupabase();
const {id} = useLocalSearchParams<{id: string}>();
const {theme, snackbar} = useDooboo();
const {bottom} = useSafeAreaInsets();
Expand Down Expand Up @@ -80,9 +82,9 @@ export default function PostDetails(): JSX.Element {
}, [post, authId]);

const handleDeletePost = useCallback(async () => {
if (!post) return;
if (!post || !supabase) return;

const result = await fetchDeletePost({id: post.id});
const result = await fetchDeletePost({id: post.id, supabase});

if (result) {
snackbar.open({text: t('common.deleteSuccess')});
Expand All @@ -95,7 +97,7 @@ export default function PostDetails(): JSX.Element {
color: 'danger',
text: t('common.unhandledError'),
});
}, [back, post, snackbar, setPosts]);
}, [post, supabase, snackbar, setPosts, back]);

const handlePressMore = useCallback(() => {
if (authId === post?.user_id) {
Expand Down Expand Up @@ -140,7 +142,7 @@ export default function PostDetails(): JSX.Element {
}, [post?.user.display_name, push]);

const handleToggleLike = async () => {
if (!authId || !post) return;
if (!authId || !post || !supabase) return;

const userLike = post.likes?.find((like) => like.user_id === authId);

Expand All @@ -155,6 +157,7 @@ export default function PostDetails(): JSX.Element {
await toggleLike({
userId: authId,
postId: post.id,
supabase,
});

setPosts((prevPosts) =>
Expand Down
24 changes: 18 additions & 6 deletions app/(home)/post/[id]/replies.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import ReplyInput from '../../../../src/components/uis/ReplyInput';
import {ImagePickerAsset} from 'expo-image-picker';
import {
getPublicUrlFromPath,
supabase,
uploadFileToSupabase,
} from '../../../../src/supabase';
import {
Expand All @@ -25,6 +24,7 @@ import {ReplyWithJoins} from '../../../../src/types';
import FallbackComponent from '../../../../src/components/uis/FallbackComponent';
import {toggleLike} from '../../../../src/apis/likeQueries';
import ErrorBoundary from 'react-native-error-boundary';
import useSupabase from '../../../../src/hooks/useSupabase';

export default function Replies({
flashListRef,
Expand All @@ -36,6 +36,7 @@ export default function Replies({
postId?: string;
replyId?: string;
}): JSX.Element {
const {supabase} = useSupabase();
const {bottom} = useSafeAreaInsets();
const {theme} = useDooboo();
const {authId} = useRecoilValue(authRecoilState);
Expand All @@ -48,7 +49,12 @@ export default function Replies({

const {error, isValidating, mutate} = useSWR<ReplyWithJoins[]>(
['replies', postId, cursor],
() => fetchReplyPagination({cursor, postId: postId as string}),
() =>
fetchReplyPagination({
cursor,
postId: postId as string,
supabase: supabase!,
}),
{
revalidateOnFocus: false,
onSuccess: (data) => {
Expand All @@ -63,7 +69,7 @@ export default function Replies({
);

const handleCreateReply = async () => {
if (!authId || !postId) return;
if (!authId || !postId || !supabase) return;

setIsCreateReplyInFlight(true);

Expand All @@ -77,12 +83,14 @@ export default function Replies({
fileType: asset.type === 'video' ? 'Video' : 'Image',
bucket: 'images',
destPath,
supabase,
});
});

const images = await Promise.all(imageUploadPromises);

const newReply = await fetchCreateReply({
supabase,
reply: {
message: reply,
user_id: authId,
Expand All @@ -93,7 +101,10 @@ export default function Replies({
.map((el) => ({
...el,
image_url: el?.image_url
? getPublicUrlFromPath(el.image_url)
? getPublicUrlFromPath({
path: el.image_url,
supabase,
})
: undefined,
})),
});
Expand Down Expand Up @@ -126,7 +137,7 @@ export default function Replies({
};

const handleToggleLike = async (replyId: string) => {
if (!authId) return;
if (!authId || !supabase) return;

const updatedReplies = replies.map((reply) => {
if (reply.id === replyId) {
Expand All @@ -153,6 +164,7 @@ export default function Replies({
await toggleLike({
userId: authId,
replyId,
supabase,
});

mutate();
Expand All @@ -162,7 +174,7 @@ export default function Replies({
const updatedReplies = replies.filter((reply) => reply.id !== replyId);
setReplies(updatedReplies);

await supabase
await supabase!
.from('replies')
.update({deleted_at: new Date().toISOString()})
.eq('id', replyId);
Expand Down
50 changes: 31 additions & 19 deletions app/(home)/post/[id]/update.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {filterUploadableAssets} from '../../../../src/utils/common';
import {RectButton} from 'react-native-gesture-handler';
import ErrorBoundary from 'react-native-error-boundary';
import FallbackComponent from '../../../../src/components/uis/FallbackComponent';
import useSupabase from '../../../../src/hooks/useSupabase';

const Container = styled.SafeAreaView`
flex: 1;
Expand All @@ -49,6 +50,7 @@ type FormData = yup.InferType<typeof schema>;

export default function PostUpdate(): JSX.Element {
const {id} = useLocalSearchParams<{id: string}>();
const {supabase} = useSupabase();
const {back} = useRouter();
const {theme, snackbar} = useDooboo();
const {authId} = useRecoilValue(authRecoilState);
Expand All @@ -68,28 +70,36 @@ export default function PostUpdate(): JSX.Element {
data: post,
error,
isValidating,
} = useSWR(id ? `post-${id}` : null, () => fetchPostById(id || ''), {
onSuccess: (data) => {
if (data) {
reset({
title: data.title,
content: data.content,
url: data?.url || undefined,
});
setAssets(
(data.images || []).map((el) => ({
uri: el.image_url as string,
type: 'image',
height: el.height || 0,
width: el.width || 0,
})),
);
}
} = useSWR(
id ? `post-${id}` : null,
() =>
fetchPostById({
id: id || '',
supabase: supabase!,
}),
{
onSuccess: (data) => {
if (data) {
reset({
title: data.title,
content: data.content,
url: data?.url || undefined,
});
setAssets(
(data.images || []).map((el) => ({
uri: el.image_url as string,
type: 'image',
height: el.height || 0,
width: el.width || 0,
})),
);
}
},
},
});
);

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

try {
const imageUploadPromises = filterUploadableAssets(assets).map(
Expand All @@ -102,6 +112,7 @@ export default function PostUpdate(): JSX.Element {
fileType: asset.type === 'video' ? 'Video' : 'Image',
bucket: 'images',
destPath,
supabase,
});
},
);
Expand Down Expand Up @@ -129,6 +140,7 @@ export default function PostUpdate(): JSX.Element {
image_url: el?.image_url || undefined,
})),
imageUrlsToDelete: deleteImageUrls,
supabase,
});

setPosts((prevPosts) =>
Expand Down
26 changes: 16 additions & 10 deletions app/(home)/post/write.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {MAX_IMAGES_UPLOAD_LENGTH} from '../../../src/utils/constants';
import CustomScrollView from '../../../src/components/uis/CustomScrollView';
import {uploadFileToSupabase} from '../../../src/supabase';
import {RectButton} from 'react-native-gesture-handler';
import useSupabase from '../../../src/hooks/useSupabase';

const Container = styled.SafeAreaView`
flex: 1;
Expand All @@ -41,6 +42,7 @@ const schema = yup.object().shape({
type FormData = yup.InferType<typeof schema>;

export default function PostWrite(): JSX.Element {
const {supabase} = useSupabase();
const {back} = useRouter();
const {theme, snackbar} = useDooboo();
const {authId} = useRecoilValue(authRecoilState);
Expand All @@ -57,7 +59,7 @@ export default function PostWrite(): JSX.Element {
});

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

setIsCreatePostInFlight(true);

Expand All @@ -71,21 +73,25 @@ export default function PostWrite(): JSX.Element {
fileType: asset.type === 'video' ? 'Video' : 'Image',
bucket: 'images',
destPath,
supabase,
});
});

const images = await Promise.all(imageUploadPromises);

const newPost = await fetchCreatePost({
title: data.title,
content: data.content,
user_id: authId,
images: images
.filter((el) => !!el)
.map((el) => ({
...el,
image_url: el?.image_url || undefined,
})),
supabase,
post: {
title: data.title,
content: data.content,
user_id: authId,
images: images
.filter((el) => !!el)
.map((el) => ({
...el,
image_url: el?.image_url || undefined,
})),
},
});

setPosts((prevPosts) => [newPost, ...prevPosts]);
Expand Down
Loading

0 comments on commit 965665e

Please sign in to comment.