Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: write and listen posts with pagination #3

Merged
merged 8 commits into from
Jul 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,28 @@ const path = require('path');

module.exports = {
root: true,
extends: [
'@dooboo/eslint-config-react-native',
],
extends: ['expo', 'prettier', 'plugin:i18n-json/recommended'],
rules: {
'eslint-comments/no-unlimited-disable': 0,
'eslint-comments/no-unused-disable': 0,
'i18n-json/identical-keys': [
2,
{
filePath: path.resolve('./assets/langs/ko.json'),
},
],
'i18n-json/sorted-keys': [
2,
{
order: 'asc',
indentSpaces: 2,
},
],
'i18n-json/valid-message-syntax': [
2,
{
syntax: path.resolve('./custom-syntax-validator.ts'),
},
],
},
};
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"CROSSPLATFORMS",
"dooboo",
"lotties",
"Onesignal",
"Pressable",
"Pretendard"
]
Expand Down
1 change: 0 additions & 1 deletion app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ if (process.env.STAGE) {
}

const DEEP_LINK_URL = '[firebaseAppId].web.app';

const buildNumber = 1;

export default ({config}: ConfigContext): ExpoConfig => ({
Expand Down
70 changes: 70 additions & 0 deletions app/(app)/(tabs)/_layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import {Pressable, View} from 'react-native';
import {Icon, useDooboo} from 'dooboo-ui';
import {Link, Redirect, Tabs, useRouter} from 'expo-router';
import {useRecoilValue} from 'recoil';

import {authRecoilState} from '../../../src/recoil/atoms';
import {t} from '../../../src/STRINGS';

function SettingsMenu(): JSX.Element {
const {theme} = useDooboo();
const {push} = useRouter();

return (
<Link asChild href="/settings">
<Pressable onPress={() => push('settings')}>
{({pressed}) => (
<Icon
color={theme.text.basic}
name="List"
size={22}
style={{marginRight: 15, opacity: pressed ? 0.5 : 1}}
/>
)}
</Pressable>
</Link>
);
}

export default function TabLayout(): JSX.Element {
const {theme} = useDooboo();
const {authId} = useRecoilValue(authRecoilState);

if (!authId) {
return <Redirect href="sign-in" />;
}

if (!authId) {
return <Redirect href="/sign-in" />;
}

return (
<Tabs
screenOptions={{
tabBarActiveTintColor: theme.role.primary,
headerStyle: {backgroundColor: theme.bg.basic},
headerTitleStyle: {color: theme.text.basic},
tabBarStyle: {backgroundColor: theme.bg.basic},
}}
>
<Tabs.Screen
name="index"
options={{
title: t('common.post'),
tabBarIcon: ({color}) => (
<Icon color={color} name="Article" size={24} />
),
headerRight: () => <View>{SettingsMenu()}</View>,
}}
/>
<Tabs.Screen
name="profile"
options={{
title: t('common.profile'),
tabBarIcon: ({color}) => <Icon color={color} name="User" size={24} />,
headerRight: () => <View>{SettingsMenu()}</View>,
}}
/>
</Tabs>
);
}
164 changes: 164 additions & 0 deletions app/(app)/(tabs)/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import styled, {css} from '@emotion/native';
import {Fab, LoadingIndicator, Typography} from 'dooboo-ui';

Check warning on line 2 in app/(app)/(tabs)/index.tsx

View workflow job for this annotation

GitHub Actions / build

'Typography' is defined but never used
import StatusBarBrightness from 'dooboo-ui/uis/StatusbarBrightness';
import {t} from '../../../src/STRINGS';

Check warning on line 4 in app/(app)/(tabs)/index.tsx

View workflow job for this annotation

GitHub Actions / build

't' is defined but never used
import {FlashList} from '@shopify/flash-list';
import {useRouter} from 'expo-router';
import {Post, User} from '../../../src/types';
import PostListItem from '../../../src/components/uis/PostListItem';
import {useEffect, useState} from 'react';
import {supabase} from '../../../src/supabase';
import {PAGE_SIZE} from '../../../src/utils/constants';

const Container = styled.View`
flex: 1;
align-self: stretch;
background-color: ${({theme}) => theme.bg.basic};
`;

type PostWithUser = Post & {user: User};

const fetchPosts = async (
page: number,
pageSize: number,
): Promise<PostWithUser[]> => {
const from = (page - 1) * pageSize;
const to = from + pageSize - 1;

const {data, error} = await supabase
.from('posts')
.select(
`
*,
user:user_id (
*
)
`,
)
.order('created_at', {ascending: false})
.range(from, to);

if (error) {
throw new Error(error.message);
}

return data as unknown as PostWithUser[];
};

const fetchPostById = async (id: string): Promise<PostWithUser | null> => {
const {data, error} = await supabase
.from('posts')
.select(
`
*,
user:user_id (
*
)
`,
)
.eq('id', id)
.single();

if (error) {
if (__DEV__) console.error('Error fetching post by ID:', error);
return null;
}

return data as unknown as PostWithUser;
};

export default function Posts(): JSX.Element {
const {push} = useRouter();
const [posts, setPosts] = useState<PostWithUser[]>([]);
const [page, setPage] = useState(0);
const [loading, setLoading] = useState(false);

const loadPosts = async (page: number) => {
setLoading(true);
try {
const newPosts = await fetchPosts(page, PAGE_SIZE);
setPosts((prevPosts) => [...prevPosts, ...newPosts]);
setPage(page);
} catch (error) {
if (__DEV__) console.error('Failed to load posts:', error);
} finally {
setLoading(false);
}
};

useEffect(() => {
loadPosts(page);
}, []);

Check warning on line 91 in app/(app)/(tabs)/index.tsx

View workflow job for this annotation

GitHub Actions / build

React Hook useEffect has a missing dependency: 'page'. Either include it or remove the dependency array

useEffect(() => {
const channel = supabase
.channel('schema-db-changes')
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'posts',
},
async (payload) => {
const newPost = await fetchPostById(payload.new.id);
if (newPost) {
setPosts((currentPosts) => [newPost, ...currentPosts]);
}
},
)
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'posts',
},
async (payload) => {
const updatedPost = await fetchPostById(payload.new.id);
if (updatedPost) {
setPosts((currentPosts) =>
currentPosts.map((post) =>
post.id === updatedPost.id ? updatedPost : post,
),
);
}
},
)
.subscribe();

return () => {
channel.unsubscribe();
};
}, []);

const loadMore = () => {
if (!loading) {
loadPosts(page + 1);
}
};

return (
<Container>
<StatusBarBrightness />
<FlashList
data={posts}
renderItem={({item}) => <PostListItem post={item} onPress={() => {}} />}
estimatedItemSize={208}
onEndReached={loadMore}
onEndReachedThreshold={0.5}
ListFooterComponent={loading ? <LoadingIndicator /> : null}
/>
<Fab
animationDuration={300}
fabIcon="Plus"
onPressFab={() => {
push('/post/write');
}}
style={css`
bottom: 16px;
`}
/>
</Container>
);
}
20 changes: 20 additions & 0 deletions app/(app)/(tabs)/profile.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {useCallback, useState} from 'react';

Check warning on line 1 in app/(app)/(tabs)/profile.tsx

View workflow job for this annotation

GitHub Actions / build

'useCallback' is defined but never used
import {View} from 'react-native';
import {Typography} from 'dooboo-ui';
import {Stack} from 'expo-router';
import {useRecoilValue} from 'recoil';

Check warning on line 5 in app/(app)/(tabs)/profile.tsx

View workflow job for this annotation

GitHub Actions / build

'useRecoilValue' is defined but never used

import {authRecoilState} from '../../../src/recoil/atoms';

Check warning on line 7 in app/(app)/(tabs)/profile.tsx

View workflow job for this annotation

GitHub Actions / build

'authRecoilState' is defined but never used
import {t} from '../../../src/STRINGS';
import {supabase} from '../../../src/supabase';

Check warning on line 9 in app/(app)/(tabs)/profile.tsx

View workflow job for this annotation

GitHub Actions / build

'supabase' is defined but never used

export default function Profile(): JSX.Element {
const [loading, setLoading] = useState(true);

Check warning on line 12 in app/(app)/(tabs)/profile.tsx

View workflow job for this annotation

GitHub Actions / build

'loading' is assigned a value but never used

Check warning on line 12 in app/(app)/(tabs)/profile.tsx

View workflow job for this annotation

GitHub Actions / build

'setLoading' is assigned a value but never used

return (
<View>
<Stack.Screen options={{title: t('common.profile')}} />
<Typography.Heading3>{t('common.profile')}</Typography.Heading3>
</View>
);
}
30 changes: 0 additions & 30 deletions app/(app)/details.tsx

This file was deleted.

Loading
Loading