Skip to content

Commit

Permalink
Use rpc function to get all stories instead of loop
Browse files Browse the repository at this point in the history
  • Loading branch information
adityapawar1 committed Mar 28, 2024
1 parent 012f270 commit d4c5945
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 44 deletions.
85 changes: 46 additions & 39 deletions src/app/(tabs)/genre/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@ import { SafeAreaView } from 'react-native-safe-area-context';

import styles from './styles';
import BackButton from '../../../components/BackButton/BackButton';
import GenreStoryPreviewCard from '../../../components/GenreStoryPreviewCard/GenreStoryPreviewCard';
import { fetchGenreStoryPreviews, fetchGenres } from '../../../queries/genres';
import { fetchStoryPreviewById } from '../../../queries/stories';
import { fetchStoryPreviewById, fetchStoryPreviewByIds } from '../../../queries/stories';
import { StoryPreview, GenreStories, Genre } from '../../../queries/types';
import globalStyles from '../../../styles/globalStyles';
import PreviewCard from '../../../components/PreviewCard/PreviewCard';
Expand All @@ -36,12 +35,7 @@ function GenreScreen() {
const [currTone, setCurrTone] = useState<string>('');
const [currTopic, setCurrTopic] = useState<string>('');
const [toneTopicFilters, setToneTopicFilters] = useState<string[]>([]);
const params = useLocalSearchParams<{ genreId: string }>();
const params2 = useLocalSearchParams<{ genreType: string }>();
const params3 = useLocalSearchParams<{ genreName: string }>();
const { genreId } = params;
const { genreType } = params2;
const { genreName } = params3;
const { genreId, genreType, genreName } = useLocalSearchParams<{ genreId: string, genreType: string, genreName: string }>();

console.log('passing in genreId params:', genreId);
console.log('testing passing in genreType', genreType);
Expand Down Expand Up @@ -77,6 +71,7 @@ function GenreScreen() {
setLoading(false);
return [];
}

console.log('testing find story IDs by Name Function:', filteredStoryIds);
return filteredStoryIds;
}
Expand Down Expand Up @@ -152,39 +147,51 @@ function GenreScreen() {

useEffect(() => {
const showAllStoryPreviews = async () => {
setLoading(true);
if (genreStoryIds.length > 0) {
setLoading(true);
const previews: StoryPreview[] = [];
const tones: string[] = [];
const topics: string[] = [];
for (const idString of genreStoryIds) {
const id = parseInt(idString, 10);
try {
const storyPreview: StoryPreview[] =
await fetchStoryPreviewById(id);
previews.push(storyPreview[0]);
storyPreview[0].tone.forEach(item => {
tones.push(item);
});
storyPreview[0].topic.forEach(item => {
topics.push(item);
});
console.log('testing storyPreview outputs:', storyPreview);
} catch (error) {
console.log(
`There was an error while trying to fetch a story preview by id: ${error}`,
);
}
}
const filteredTopics: string[] = topics.filter(
(item): item is string => item !== null,
);
const filteredTones: string[] = tones.filter(
(item): item is string => item !== null,
);
const previews: StoryPreview[] = await fetchStoryPreviewByIds(genreStoryIds);

const tones: string[] = previews
.reduce((acc: string[], current: StoryPreview) => {
return acc.concat(current.tone);
}, [] as string[])
.filter(tone => tone !== null);
const topics: string[] = previews
.reduce((acc: string[], current: StoryPreview) => {
return acc.concat(current.topic);
}, [] as string[])
.filter(topic => topic !== null);

// for (const idString of genreStoryIds) {
// const id = parseInt(idString, 10);
// try {
// const storyPreview: StoryPreview[] =
// await fetchStoryPreviewById(id);
// previews.push(storyPreview[0]);
// storyPreview[0].tone.forEach(item => {
// tones.push(item);
// });
// storyPreview[0].topic.forEach(item => {
// topics.push(item);
// });
// console.log('testing storyPreview outputs:', storyPreview);
// } catch (error) {
// console.log(
// `There was an error while trying to fetch a story preview by id: ${error}`,
// );
// }
// }
// const filteredTopics: string[] = topics.filter(
// (item): item is string => item !== null,
// );
// const filteredTones: string[] = tones.filter(
// (item): item is string => item !== null,
// );

console.log('testing storyPreview outputs:', previews);
setAllStoryPreviews(previews.flat());
setgenreTopics(filteredTopics);
setgenreTones(filteredTones);
setgenreTopics(topics);
setgenreTones(tones);
console.log('testing tone usestate');
setLoading(false);
} else {
Expand Down
10 changes: 6 additions & 4 deletions src/app/(tabs)/search/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const getRecentSearch = async () => {
const jsonValue = await AsyncStorage.getItem('GWN_RECENT_SEARCHES_ARRAY');
return jsonValue != null ? JSON.parse(jsonValue) : [];
} catch (error) {
console.log(error);
console.error(error);
}
};

Expand All @@ -38,7 +38,7 @@ const setRecentSearch = async (searchResult: RecentSearch[]) => {
const jsonValue = JSON.stringify(searchResult);
await AsyncStorage.setItem('GWN_RECENT_SEARCHES_ARRAY', jsonValue);
} catch (error) {
console.log(error);
console.error(error);
}
};

Expand All @@ -47,7 +47,7 @@ const getRecentStory = async () => {
const jsonValue = await AsyncStorage.getItem('GWN_RECENT_STORIES_ARRAY');
return jsonValue != null ? JSON.parse(jsonValue) : [];
} catch (error) {
console.log(error);
console.error(error);
}
};

Expand All @@ -56,7 +56,7 @@ const setRecentStory = async (recentStories: StoryPreview[]) => {
const jsonValue = JSON.stringify(recentStories);
await AsyncStorage.setItem('GWN_RECENT_STORIES_ARRAY', jsonValue);
} catch (error) {
console.log(error);
console.error(error);
}
};

Expand Down Expand Up @@ -91,12 +91,14 @@ function SearchScreen() {
setSearchResults([]);
return;
}

const updatedData = allStories.filter((item: StoryPreview) => {
const title = `${item.title.toUpperCase()})`;
const author = `${item.author_name.toUpperCase()})`;
const text_data = text.toUpperCase();
return title.indexOf(text_data) > -1 || author.indexOf(text_data) > -1;
});

setSearch(text);
setSearchResults(updatedData);
setShowGenreCarousals(false);
Expand Down
4 changes: 3 additions & 1 deletion src/components/PreviewCard/PreviewCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import * as cheerio from 'cheerio';
import styles from './styles';
import globalStyles from '../../styles/globalStyles';

const placeholderImage = "https://gwn-uploads.s3.amazonaws.com/wp-content/uploads/2021/10/10120952/Girls-Write-Now-logo-avatar.png"

type PreviewCardProps = {
title: string;
image: string;
Expand Down Expand Up @@ -38,7 +40,7 @@ function PreviewCard({
</Text>
</View>
<View style={styles.body}>
<Image style={styles.image} source={{ uri: image }} />
<Image style={styles.image} source={{ uri: image == "" ? placeholderImage : image }} />
<View style={styles.cardTextContainer}>
<View style={styles.authorContainer}>
<Image style={styles.authorImage} source={{ uri: authorImage }} />
Expand Down
20 changes: 20 additions & 0 deletions src/queries/stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,23 @@ export async function fetchStoryPreviewById(
return data;
}
}

export async function fetchStoryPreviewByIds(
storyIds: number[],
): Promise<StoryPreview[]> {
const { data, error } = await supabase.rpc(
'curr_story_preview_by_ids',
{
input_ids: storyIds,
},
);
if (error) {
console.log(error);
throw new Error(
`An error occured when trying to fetch story preview by IDs: ${error}`,
);
} else {
return data;
}
}

0 comments on commit d4c5945

Please sign in to comment.