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: refactored search #105

Merged
merged 1 commit into from
Dec 5, 2023
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
86 changes: 39 additions & 47 deletions src/screens/search/form-for-search.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { Picker } from '@react-native-picker/picker';
import React from 'react';
import { useEffect, useMemo, useState } from 'react';
import type { SubmitHandler } from 'react-hook-form';
import { useForm } from 'react-hook-form';
import * as z from 'zod';

import { Button, ControlledInput, ScrollView, View } from '@/ui';
import { Button, ControlledInput, ScrollView, Text, View } from '@/ui';

export const SEARCH_BY_USERNAME = 1;
export const SEARCH_BY_CONTENT = 2;
export const SEARCH_BY_HASHTAG = 3;

export const schema = z.object({
username: z
.string()
.max(50, 'First Name cannot exceed 50 characters')
.optional(),
content: z
.string()
.max(50, 'Last Name cannot exceed 50 characters')
.optional(),
hashtag: z
.string()
.max(50, 'Last Name cannot exceed 50 characters')
.optional(),
search: z.string().max(50, 'Search cannot exceed 50 characters'),
type: z.number(),
});

export type FormType = z.infer<typeof schema>;
Expand All @@ -30,50 +26,46 @@ export interface SearchFormProps {
export const FormForSearch: React.FC<SearchFormProps> = ({
onSearchSubmit = () => {},
}) => {
const { handleSubmit, control, watch } = useForm<FormType>({
const { handleSubmit, control, setValue } = useForm<FormType>({
resolver: zodResolver(schema),
});

const watchedFields = watch();
const [isAnyFieldFilled, setIsAnyFieldFilled] =
React.useState<boolean>(false);
const typeOptions = useMemo(() => ['username', 'content', 'hashtag'], []);
const [type, setTypeOption] = useState<string>(typeOptions[0]);

React.useEffect(() => {
const anyFieldFilled = Object.values(watchedFields).some(
(fieldValue) => fieldValue && fieldValue.trim() !== ''
useEffect(() => {
setValue(
'type',
type === typeOptions[0]
? SEARCH_BY_USERNAME
: type === typeOptions[1]
? SEARCH_BY_CONTENT
: SEARCH_BY_HASHTAG
);
setIsAnyFieldFilled(anyFieldFilled);
}, [watchedFields]);

const shouldDisableField = (fieldName: keyof FormType) => {
const fieldValue = watchedFields[fieldName];
const isFieldEmpty = !fieldValue || fieldValue.trim() === '';
return isAnyFieldFilled && isFieldEmpty;
};
}, [type, setValue, typeOptions]);

return (
<View className="flex-1 p-4">
<ScrollView className="flex-1 p-4">
<ControlledInput
testID="username-input"
control={control}
name="username"
label="username"
disabled={shouldDisableField('username')}
/>
<ControlledInput
testID="content-input"
control={control}
name="content"
label="content"
disabled={shouldDisableField('content')}
/>
<Text className="py-2 text-center text-2xl font-bold">Search By</Text>
<ScrollView className="flex-1 ">
<View className="flex p-2">
<Picker
testID="type-input"
selectedValue={type}
className="inline rounded-full bg-blue-100 px-4 py-3"
onValueChange={(itemValue) => {
setTypeOption(itemValue);
}}
>
{typeOptions.map((option, index) => (
<Picker.Item key={index} label={option} value={option} />
))}
</Picker>
</View>
<ControlledInput
testID="hashtag-input"
testID="search-input"
control={control}
name="hashtag"
label="hashtag"
disabled={shouldDisableField('hashtag')}
name="search"
/>
</ScrollView>

Expand Down
20 changes: 12 additions & 8 deletions src/screens/search/search-bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import { getUserState } from '@/core';

import type { FormType } from './form-for-search';
import { FormForSearch } from './form-for-search';
import {
SEARCH_BY_CONTENT,
SEARCH_BY_HASHTAG,
SEARCH_BY_USERNAME,
} from './form-for-search';
import type { SearchStackParamList } from './search-navigator';

const whenSearch = async (
Expand All @@ -18,30 +23,29 @@ const whenSearch = async (
console.log(currentUser);

console.log(data);
if (data.username && data.username.trim() !== '') {

if (data.type === SEARCH_BY_USERNAME && data.search.trim() !== '') {
try {
const { data: users } = await client.identity.get(
`/api/filter/${currentUser?.id}/${data.username}`
`/api/filter/${currentUser?.id}/${data.search}`
);
navigate('Users', { users });
} catch (error) {
console.error('Error searching by username:', error);
}
}
if (data.content && data.content.trim() !== '') {
} else if (data.type === SEARCH_BY_CONTENT && data.search.trim() !== '') {
try {
const { data: snapsFromContent } = await client.content.get(
`/api/filter/content?user_id=${currentUser?.id}&content=${data.content}`
`/api/filter/content?user_id=${currentUser?.id}&content=${data.search}`
);
navigate('SnapList', { snaps: snapsFromContent.snaps });
} catch (error) {
console.error('Error searching by content:', error);
}
}
if (data.hashtag && data.hashtag.trim() !== '') {
} else if (data.type === SEARCH_BY_HASHTAG && data.search.trim() !== '') {
try {
const { data: snapsFromHashtags } = await client.content.get(
`/api/filter/hashtag?user_id=${currentUser?.id}&hashtag=${data.hashtag}`
`/api/filter/hashtag?user_id=${currentUser?.id}&hashtag=${data.search}`
);
navigate('SnapList', { snaps: snapsFromHashtags.snaps });
} catch (error) {
Expand Down