fix notice status

This commit is contained in:
Patryk
2025-06-08 10:30:14 +02:00
parent ca59c94783
commit e2e5543e0d
5 changed files with 523 additions and 459 deletions

View File

@@ -0,0 +1,12 @@
import axios from "axios";
import FormData from "form-data";
const API_URL = "https://hopp.zikor.pl/api/v1";
export async function listOrders() {
const response = await fetch(`${API_URL}/orders/get/all`);
const data = await response.json();
if (!response.ok) {
throw new Error(response.toString());
}
return data;
}

View File

@@ -1,11 +1,11 @@
import { useNoticesStore } from "@/store/noticesStore";
import { NoticeCard } from "@/components/NoticeCard";
import {Button} from "react-native";
import {Box} from "@/components/ui/box";
import {Text} from "@/components/ui/text";
import {VStack} from "@/components/ui/vstack";
import {ActivityIndicator, FlatList } from "react-native";
import {useEffect, useState} from "react";
import { Button } from "react-native";
import { Box } from "@/components/ui/box";
import { Text } from "@/components/ui/text";
import { VStack } from "@/components/ui/vstack";
import { ActivityIndicator, FlatList } from "react-native";
import { useEffect, useState } from "react";
export default function UserNotices() {
const { notices, fetchNotices } = useNoticesStore();
@@ -26,50 +26,63 @@ export default function UserNotices() {
loadNotices();
}, []);
const userNotices = notices.filter(notice => notice.clientId === currentUserId);
const userNotices = notices
.filter((notice) => notice.clientId === currentUserId)
.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate));
if (isLoading) {
return <ActivityIndicator />;
}
return (
<VStack className="p-4">
<Text className="text-2xl font-bold mb-4">Moje ogłoszenia</Text>
{userNotices.length > 0 ? (
<FlatList
data={userNotices}
numColumns={2}
columnWrapperStyle={{ marginBottom: 10, justifyContent: "space-between" }}
renderItem={({ item }) => (
<Box className="flex-1">
<NoticeCard notice={item} />
<Box className="flex-row justify-between mt-2">
<Button
title="Promuj"
onPress={() => {
// TODO: Implementacja promocji ogłoszenia
console.log(`Promuj ogłoszenie ${item.noticeId}`);
}}
className="bg-primary-500 py-2 px-4 rounded-md"
>
</Button>
<Button
title="Podbij"
onPress={() => {
// TODO: Implementacja podbicia ogłoszenia
console.log(`Podbij ogłoszenie ${item.noticeId}`);
}}
className="bg-primary-500 py-2 px-4 rounded-md"
>
</Button>
</Box>
</Box>
<VStack className="p-4">
{/* <Text className="text-2xl font-bold mb-4">Moje ogłoszenia</Text> */}
{userNotices.length > 0 ? (
<FlatList
data={userNotices}
// numColumns={1}
// columnWrapperStyle={{
// marginBottom: 10,
// justifyContent: "space-between",
// }}
renderItem={({ item }) => (
<Box className="flex-1 mb-4 pb-2 bg-white rounded-lg">
<NoticeCard notice={item} />
<Box className="flex-row justify-between mt-2">
{item.status === "ACTIVE" ? (
<Button
title="Usuń"
onPress={() => {
console.log(`Promuj ogłoszenie ${item.noticeId}`);
}}
className="bg-primary-500 py-2 px-4 rounded-md"
></Button>
) : (
<Button
title="Aktywj"
onPress={() => {
console.log(`Promuj ogłoszenie ${item.noticeId}`);
}}
className="bg-primary-500 py-2 px-4 rounded-md"
></Button>
)}
keyExtractor={(item) => item.noticeId.toString()}
/>
) : (
<Text>Nie masz żadnych ogłoszeń.</Text>
)}
</VStack>
<Button
title="Podbij"
onPress={() => {
// TODO: Implementacja podbicia ogłoszenia
console.log(`Podbij ogłoszenie ${item.noticeId}`);
}}
className="bg-primary-500 py-2 px-4 rounded-md"
></Button>
</Box>
</Box>
)}
keyExtractor={(item) => item.noticeId.toString()}
/>
) : (
<Text>Nie masz żadnych ogłoszeń.</Text>
)}
</VStack>
);
}
}

View File

@@ -34,11 +34,14 @@ export default function Home() {
const notices = useNoticesStore((state) => state.notices);
// console.log("Notices:", notices);
// console.log("Notices length:", notices.length);
const latestNotices = [...notices]
const activeNotices = notices.filter((notice) => notice.status === "ACTIVE");
// console.log("Activer Notices:", activeNotices.length);
const latestNotices = [...activeNotices]
.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate))
.slice(0, 6);
const recomendedNotices = [...notices]
const recomendedNotices = [...activeNotices]
.sort(() => Math.random() - 0.5)
.slice(0, 6);
@@ -47,13 +50,13 @@ export default function Home() {
{/* <View> */}
<SearchSection />
<ScrollView showsVerticalScrollIndicator={false}>
<CategorySection title="Polecane kategorie" notices={notices} />
<CategorySection title="Polecane kategorie" notices={activeNotices} />
<NoticeSection
title="Najnowsze ogłoszenia"
notices={latestNotices}
ctaLink="/notices?sort=latest"
/>
<UserSection title="Popularni sprzedawcy" notices={notices} />
<UserSection title="Popularni sprzedawcy" notices={activeNotices} />
<NoticeSection
title="Proponowane ogłoszenia"
notices={recomendedNotices}

View File

@@ -1,4 +1,10 @@
import { FlatList, Text, ActivityIndicator, RefreshControl, Dimensions } from "react-native";
import {
FlatList,
Text,
ActivityIndicator,
RefreshControl,
Dimensions,
} from "react-native";
import { useState, useEffect } from "react";
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import { useNoticesStore } from "@/store/noticesStore";
@@ -11,345 +17,369 @@ import { listCategories } from "@/api/categories";
import { FormControl, FormControlLabel } from "@/components/ui/form-control";
import { Input, InputField } from "@/components/ui/input";
import { HStack } from "@/components/ui/hstack";
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import { KeyboardAvoidingView, Platform } from "react-native";
import {
Actionsheet,
ActionsheetContent,
ActionsheetItem,
ActionsheetItemText,
ActionsheetDragIndicator,
ActionsheetDragIndicatorWrapper,
ActionsheetBackdrop,
Actionsheet,
ActionsheetContent,
ActionsheetItem,
ActionsheetItemText,
ActionsheetDragIndicator,
ActionsheetDragIndicatorWrapper,
ActionsheetBackdrop,
} from "@/components/ui/actionsheet";
import {
Select,
SelectTrigger,
SelectInput,
SelectIcon,
SelectPortal,
SelectBackdrop,
SelectContent,
SelectDragIndicator,
SelectDragIndicatorWrapper,
SelectItem,
Select,
SelectTrigger,
SelectInput,
SelectIcon,
SelectPortal,
SelectBackdrop,
SelectContent,
SelectDragIndicator,
SelectDragIndicatorWrapper,
SelectItem,
} from "@/components/ui/select";
import { ScrollView } from "react-native-gesture-handler";
export default function Notices() {
// Hooks
const { notices, fetchNotices } = useNoticesStore();
const [refreshing, setRefreshing] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [showActionsheet, setShowActionsheet] = useState(false);
const [showSortSheet, setShowSortSheet] = useState(false);
const [categories, setCategories] = useState([]);
const [filteredNotices, setFilteredNotices] = useState([]);
const params = useLocalSearchParams();
const router = useRouter();
// Hooks
const { notices, fetchNotices } = useNoticesStore();
const [refreshing, setRefreshing] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [showActionsheet, setShowActionsheet] = useState(false);
const [showSortSheet, setShowSortSheet] = useState(false);
const [categories, setCategories] = useState([]);
const [filteredNotices, setFilteredNotices] = useState([]);
const params = useLocalSearchParams();
const router = useRouter();
useEffect(() => {
const fetchSelectItems = async () => {
try {
const data = await listCategories();
if (Array.isArray(data)) {
setCategories(data);
} else {
console.error('listCategories did not return an array:', data);
setError(new Error('Invalid categories data'));
}
} catch (error) {
console.error('Error fetching select items:', error);
setError(error);
}
};
fetchSelectItems();
}, []);
useEffect(() => {
loadData();
}, []);
useEffect(() => {
let result = notices;
if (params.category) {
result = result.filter(notice => notice.category === params.category);
useEffect(() => {
const fetchSelectItems = async () => {
try {
const data = await listCategories();
if (Array.isArray(data)) {
setCategories(data);
} else {
console.error("listCategories did not return an array:", data);
setError(new Error("Invalid categories data"));
}
} catch (error) {
console.error("Error fetching select items:", error);
setError(error);
}
};
fetchSelectItems();
}, []);
if (params.sort) {
if( params.sort == "latest"){
result = [...result].sort(
(a, b) => new Date(b.publishDate) - new Date(a.publishDate)
);
}else if (params.sort == "oldest") {
result = [...result].sort(
(a, b) => new Date(a.publishDate) - new Date(b.publishDate)
);
}else if (params.sort == "cheapest") {
result = [...result].sort((a, b) => {
const priceA = parseFloat(a.price);
const priceB = parseFloat(b.price);
return isNaN(priceA) || isNaN(priceB) ? 0 : priceA - priceB;
});
}else if (params.sort == "expensive") {
result = [...result].sort((a, b) => {
const priceA = parseFloat(a.price);
const priceB = parseFloat(b.price);
return isNaN(priceA) || isNaN(priceB) ? 0 : priceB - priceA;
});
}
useEffect(() => {
loadData();
}, []);
}
useEffect(() => {
let result = notices.filter((notice) => notice.status === "ACTIVE");
if (params.priceFrom) {
result = result.filter(notice => {
const price = parseFloat(notice.price);
const priceFrom = parseFloat(params.priceFrom);
return !isNaN(price) && price >= priceFrom;
});
}
if (params.category) {
result = result.filter((notice) => notice.category === params.category);
}
if (params.priceTo) {
result = result.filter(notice => {
const price = parseFloat(notice.price);
const priceTo = parseFloat(params.priceTo);
return !isNaN(price) && price <= priceTo;
});
}
if (params.sort) {
if (params.sort == "latest") {
result = [...result].sort(
(a, b) => new Date(b.publishDate) - new Date(a.publishDate)
);
} else if (params.sort == "oldest") {
result = [...result].sort(
(a, b) => new Date(a.publishDate) - new Date(b.publishDate)
);
} else if (params.sort == "cheapest") {
result = [...result].sort((a, b) => {
const priceA = parseFloat(a.price);
const priceB = parseFloat(b.price);
return isNaN(priceA) || isNaN(priceB) ? 0 : priceA - priceB;
});
} else if (params.sort == "expensive") {
result = [...result].sort((a, b) => {
const priceA = parseFloat(a.price);
const priceB = parseFloat(b.price);
return isNaN(priceA) || isNaN(priceB) ? 0 : priceB - priceA;
});
}
}
if (params.priceFrom) {
result = result.filter((notice) => {
const price = parseFloat(notice.price);
const priceFrom = parseFloat(params.priceFrom);
return !isNaN(price) && price >= priceFrom;
});
}
if (params.search) {
const searchTerm = params.search.toLowerCase();
result = result.filter(notice => {
return notice.title.toLowerCase().includes(searchTerm);
});
}
if (params.priceTo) {
result = result.filter((notice) => {
const price = parseFloat(notice.price);
const priceTo = parseFloat(params.priceTo);
return !isNaN(price) && price <= priceTo;
});
}
setFilteredNotices(result);
}, [notices,
if (params.search) {
const searchTerm = params.search.toLowerCase();
result = result.filter((notice) => {
return notice.title.toLowerCase().includes(searchTerm);
});
}
setFilteredNotices(result);
}, [
notices,
params.category,
params.sort,
params.priceFrom,
params.priceTo,
params.search]);
params.search,
]);
let filterActive =
!!params.category ||
!!params.sort ||
!!params.priceFrom ||
!!params.priceTo ||
!!params.search;
let filterActive = !!params.category || !!params.sort || !!params.priceFrom || !!params.priceTo || !!params.search;
const loadData = async () => {
setIsLoading(true);
try {
await fetchNotices();
setError(null);
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
const handleCategorySelect = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, category: value }
});
};
const handlePriceFrom = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, priceFrom: value }
});
const loadData = async () => {
setIsLoading(true);
try {
await fetchNotices();
setError(null);
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
const handlePriceTo = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, priceTo: value }
});
const handleCategorySelect = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, category: value },
});
};
const handlePriceFrom = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, priceFrom: value },
});
};
const handlePriceTo = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, priceTo: value },
});
};
const handleClose = () => setShowActionsheet(false);
const handleSort = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, sort: value },
});
setShowSortSheet(false);
};
const onRefresh = async () => {
setRefreshing(true);
try {
await fetchNotices();
} catch (err) {
setError(err);
} finally {
setRefreshing(false);
}
};
const handleClose = () => setShowActionsheet(false);
if (isLoading && !refreshing) {
return <ActivityIndicator />;
}
const handleSort = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, sort: value }
});
setShowSortSheet(false);
}
if (error) {
return <Text>Nie udało się pobrać listy. {error.message}</Text>;
}
const onRefresh = async () => {
setRefreshing(true);
try {
await fetchNotices();
} catch (err) {
setError(err);
} finally {
setRefreshing(false);
}
};
const SCREEN_HEIGHT = Dimensions.get("window").height;
if (isLoading && !refreshing) {
return <ActivityIndicator />;
}
const selectedCategory =
(params.category &&
categories?.find((cat) => cat.value === params.category)) ||
null;
if (error) {
return <Text>Nie udało się pobrać listy. {error.message}</Text>;
}
const SCREEN_HEIGHT = Dimensions.get('window').height;
const selectedCategory = params.category && categories?.find(
(cat) => cat.value === params.category
) || null;
return (
<>
<Box style={{ flexDirection: "row", padding: 8, paddingTop: 16, paddingBottom: 16, backgroundColor: "white", alignItems: "center", justifyContent: "space-between" }}>
<Box style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
<Button variant="outline" onPress={() => setShowActionsheet(true)}>
<ButtonText>Filtruj</ButtonText>
<Ionicons name="filter-outline" size={20} color="black" />
</Button>
<Button variant="outline" onPress={() => setShowSortSheet(true)}>
<Ionicons name="chevron-expand-outline" size={20} color="black" />
</Button>
</Box>
{filterActive && (
<Button variant="link" onPress={() => router.replace("/notices")}>
<ButtonText>Wyczyść</ButtonText>
</Button>
)}
</Box>
<Actionsheet isOpen={showActionsheet} onClose={handleClose}>
<ActionsheetBackdrop />
<ActionsheetContent style={{ maxHeight: SCREEN_HEIGHT * 0.6, width: '100%' }} >
<KeyboardAwareScrollView
contentContainerStyle={{ flexGrow: 1, width: '100%' }}
enableOnAndroid={true}
extraScrollHeight={40}
return (
<>
<Box
style={{
flexDirection: "row",
padding: 8,
paddingTop: 16,
paddingBottom: 16,
backgroundColor: "white",
alignItems: "center",
justifyContent: "space-between",
}}
>
<ActionsheetDragIndicatorWrapper>
<ActionsheetDragIndicator />
</ActionsheetDragIndicatorWrapper>
<Box className="mb-4" style={{ width: "100%" }}>
<HStack space="md" style={{ width: "100%" }}>
<FormControl
style={{ flex: 1 }}>
<Input>
<InputField
keyboardType="numeric"
placeholder="Od:"
value={params.priceFrom || ''}
onChangeText={handlePriceFrom}
/>
</Input>
</FormControl>
<FormControl
style={{ flex: 1 }}>
<Input>
<InputField
keyboardType="numeric"
placeholder="Do:"
value={params.priceTo || ''}
onChangeText={handlePriceTo}
/>
</Input>
</FormControl>
</HStack>
</Box>
<Box className="mb-4" style={{ flex: 1 }}>
<Select
style={{ flex: 1 }}
selectedValue={params.category || ''}
onValueChange={handleCategorySelect}
>
<SelectTrigger variant="outline" size="md">
<SelectInput
style={{ flex: 1 }}
placeholder="Wybierz kategorię"
value={selectedCategory ? selectedCategory.label : ""}
/>
<SelectIcon style={{ marginRight: 12 }} as={ChevronDownIcon} />
</SelectTrigger>
<SelectPortal>
<SelectBackdrop />
<SelectContent
style={{ maxHeight: SCREEN_HEIGHT * 0.6}}
>
<SelectDragIndicatorWrapper>
<SelectDragIndicator />
</SelectDragIndicatorWrapper>
<FlatList
style={{ width: '100%' }}
data={categories}
keyExtractor={(item) => item.value?.toString() || item.id?.toString() || Math.random().toString()}
renderItem={({ item }) => (
<SelectItem
label={item.label}
value={item.value}
/>
)}
/>
</SelectContent>
</SelectPortal>
</Select>
</Box>
</KeyboardAwareScrollView>
</ActionsheetContent>
</Actionsheet>
<Actionsheet isOpen={showSortSheet} onClose={() => setShowSortSheet(false)}>
<ActionsheetBackdrop />
<ActionsheetContent>
<ActionsheetDragIndicatorWrapper>
<ActionsheetDragIndicator />
</ActionsheetDragIndicatorWrapper>
<ActionsheetItem
className={ !params.sort ? 'bg-gray-200' : ''}
onPress={() => handleSort()}>
<ActionsheetItemText>Trafność</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={ params.sort == 'latest' ? 'bg-gray-200' : ''}
onPress={() => handleSort('latest')}>
<ActionsheetItemText>Najnowsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={ params.sort == 'oldest' ? 'bg-gray-200' : ''}
onPress={() => handleSort('oldest')}>
<ActionsheetItemText>Najstarsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={ params.sort == 'cheapest' ? 'bg-gray-200' : ''}
onPress={() => handleSort('cheapest')}>
<ActionsheetItemText>Najtańsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={ params.sort == 'expensive' ? 'bg-gray-200' : ''}
onPress={() => handleSort('expensive')}>
<ActionsheetItemText>Najdroższe</ActionsheetItemText>
</ActionsheetItem>
</ActionsheetContent>
</Actionsheet>
<FlatList
data={filteredNotices}
numColumns={2}
columnWrapperStyle={{ gap: 8, marginHorizontal: 8 }}
contentContainerStyle={{ paddingBottom: 16 }}
renderItem={({ item }) => <NoticeCard notice={item} />}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={["#3b82f6"]}
tintColor="#3b82f6"
<Box style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
<Button variant="outline" onPress={() => setShowActionsheet(true)}>
<ButtonText>Filtruj</ButtonText>
<Ionicons name="filter-outline" size={20} color="black" />
</Button>
<Button variant="outline" onPress={() => setShowSortSheet(true)}>
<Ionicons name="chevron-expand-outline" size={20} color="black" />
</Button>
</Box>
{filterActive && (
<Button variant="link" onPress={() => router.replace("/notices")}>
<ButtonText>Wyczyść</ButtonText>
</Button>
)}
</Box>
<Actionsheet isOpen={showActionsheet} onClose={handleClose}>
<ActionsheetBackdrop />
<ActionsheetContent
style={{ maxHeight: SCREEN_HEIGHT * 0.6, width: "100%" }}
>
<KeyboardAwareScrollView
contentContainerStyle={{ flexGrow: 1, width: "100%" }}
enableOnAndroid={true}
extraScrollHeight={40}
>
<ActionsheetDragIndicatorWrapper>
<ActionsheetDragIndicator />
</ActionsheetDragIndicatorWrapper>
<Box className="mb-4" style={{ width: "100%" }}>
<HStack space="md" style={{ width: "100%" }}>
<FormControl style={{ flex: 1 }}>
<Input>
<InputField
keyboardType="numeric"
placeholder="Od:"
value={params.priceFrom || ""}
onChangeText={handlePriceFrom}
/>
}
/>
</>
);
}
</Input>
</FormControl>
<FormControl style={{ flex: 1 }}>
<Input>
<InputField
keyboardType="numeric"
placeholder="Do:"
value={params.priceTo || ""}
onChangeText={handlePriceTo}
/>
</Input>
</FormControl>
</HStack>
</Box>
<Box className="mb-4" style={{ flex: 1 }}>
<Select
style={{ flex: 1 }}
selectedValue={params.category || ""}
onValueChange={handleCategorySelect}
>
<SelectTrigger variant="outline" size="md">
<SelectInput
style={{ flex: 1 }}
placeholder="Wybierz kategorię"
value={selectedCategory ? selectedCategory.label : ""}
/>
<SelectIcon
style={{ marginRight: 12 }}
as={ChevronDownIcon}
/>
</SelectTrigger>
<SelectPortal>
<SelectBackdrop />
<SelectContent style={{ maxHeight: SCREEN_HEIGHT * 0.6 }}>
<SelectDragIndicatorWrapper>
<SelectDragIndicator />
</SelectDragIndicatorWrapper>
<FlatList
style={{ width: "100%" }}
data={categories}
keyExtractor={(item) =>
item.value?.toString() ||
item.id?.toString() ||
Math.random().toString()
}
renderItem={({ item }) => (
<SelectItem label={item.label} value={item.value} />
)}
/>
</SelectContent>
</SelectPortal>
</Select>
</Box>
</KeyboardAwareScrollView>
</ActionsheetContent>
</Actionsheet>
<Actionsheet
isOpen={showSortSheet}
onClose={() => setShowSortSheet(false)}
>
<ActionsheetBackdrop />
<ActionsheetContent>
<ActionsheetDragIndicatorWrapper>
<ActionsheetDragIndicator />
</ActionsheetDragIndicatorWrapper>
<ActionsheetItem
className={!params.sort ? "bg-gray-200" : ""}
onPress={() => handleSort()}
>
<ActionsheetItemText>Trafność</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={params.sort == "latest" ? "bg-gray-200" : ""}
onPress={() => handleSort("latest")}
>
<ActionsheetItemText>Najnowsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={params.sort == "oldest" ? "bg-gray-200" : ""}
onPress={() => handleSort("oldest")}
>
<ActionsheetItemText>Najstarsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={params.sort == "cheapest" ? "bg-gray-200" : ""}
onPress={() => handleSort("cheapest")}
>
<ActionsheetItemText>Najtańsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={params.sort == "expensive" ? "bg-gray-200" : ""}
onPress={() => handleSort("expensive")}
>
<ActionsheetItemText>Najdroższe</ActionsheetItemText>
</ActionsheetItem>
</ActionsheetContent>
</Actionsheet>
<FlatList
data={filteredNotices}
numColumns={2}
columnWrapperStyle={{ gap: 8, marginHorizontal: 8 }}
contentContainerStyle={{ paddingBottom: 16 }}
renderItem={({ item }) => <NoticeCard notice={item} />}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={["#3b82f6"]}
tintColor="#3b82f6"
/>
}
/>
</>
);
}

View File

@@ -1,111 +1,117 @@
import {Box} from "@/components/ui/box";
import {Card} from "@/components/ui/card";
import {Heading} from "@/components/ui/heading";
import {Image} from "@/components/ui/image";
import {Text} from "@/components/ui/text";
import {VStack} from "@/components/ui/vstack";
import {Link} from "expo-router";
import {Pressable, ActivityIndicator, View} from "react-native";
import {useWishlist} from "@/store/wishlistStore";
import {useNoticesStore} from "@/store/noticesStore";
import {Ionicons} from "@expo/vector-icons";
import {useEffect, useState} from "react";
import { Box } from "@/components/ui/box";
import { Card } from "@/components/ui/card";
import { Heading } from "@/components/ui/heading";
import { Image } from "@/components/ui/image";
import { Text } from "@/components/ui/text";
import { VStack } from "@/components/ui/vstack";
import { Link } from "expo-router";
import { Pressable, ActivityIndicator, View } from "react-native";
import { useWishlist } from "@/store/wishlistStore";
import { useNoticesStore } from "@/store/noticesStore";
import { Ionicons } from "@expo/vector-icons";
import { useEffect, useState } from "react";
export function NoticeCard({notice}) {
const noticeId = notice?.noticeId;
export function NoticeCard({ notice }) {
const noticeId = notice?.noticeId;
const toggleNoticeInWishlist = useWishlist((state) => state.toggleNoticeInWishlist);
const isInWishlist = useWishlist((state) =>
noticeId ? state.wishlistNotices.some((item) => item.noticeId === noticeId) : false
);
const toggleNoticeInWishlist = useWishlist(
(state) => state.toggleNoticeInWishlist
);
const isInWishlist = useWishlist((state) =>
noticeId
? state.wishlistNotices.some((item) => item.noticeId === noticeId)
: false
);
const [image, setImage] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [image, setImage] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const {getAllImagesByNoticeId} = useNoticesStore();
const { getAllImagesByNoticeId } = useNoticesStore();
useEffect(() => {
let isMounted = true;
useEffect(() => {
let isMounted = true;
const fetchImage = async () => {
if (!noticeId) {
if (isMounted) {
setImage("https://http.cat/404.jpg");
setIsLoading(false);
}
return;
}
const fetchImage = async () => {
if (!noticeId) {
if (isMounted) {
setImage("https://http.cat/404.jpg");
setIsLoading(false);
}
return;
}
setIsLoading(true);
try {
const images = await getAllImagesByNoticeId(noticeId);
if (isMounted) {
setImage(images && images.length > 0 ? images[0] : "https://http.cat/404.jpg");
}
} catch (error) {
console.error(`Error while loading image: ${error}`);
if (isMounted) {
setImage("https://http.cat/404.jpg");
}
} finally {
if (isMounted) {
setIsLoading(false);
}
}
};
setIsLoading(true);
try {
const images = await getAllImagesByNoticeId(noticeId);
if (isMounted) {
setImage(
images && images.length > 0 ? images[0] : "https://http.cat/404.jpg"
);
}
} catch (error) {
console.error(`Error while loading image: ${error}`);
if (isMounted) {
setImage("https://http.cat/404.jpg");
}
} finally {
if (isMounted) {
setIsLoading(false);
}
}
};
fetchImage();
fetchImage();
return () => {
isMounted = false;
};
}, [noticeId]);
return () => {
isMounted = false;
};
}, [noticeId]);
if (!notice) {
return <View style={{flex: 1}} />;
}
if (!notice) {
return <View style={{ flex: 1 }} />;
}
return (
<Link href={`/notice/${noticeId}`} asChild>
<Pressable className="flex-1">
<Card className="p-0 rounded-lg max-w-[460px] flex-1">
{isLoading ? (
<Box className="h-auto w-full rounded-md aspect-[1/1] bg-gray-100 items-center justify-center">
<ActivityIndicator size="large" color="#3b82f6" />
</Box>
) : (
<Image
source={{
uri: image,
}}
className="h-auto w-full rounded-md aspect-[1/1]"
alt="image"
resizeMode="cover"
/>
)}
<VStack className="p-2">
<Text className="text-sm font-normal mb-2 text-typography-700">
{notice.title}
</Text>
<Box className="flex-row items-center">
<Heading size="md" className="flex-1">
{notice.price}
</Heading>
<Pressable
onPress={() => {
toggleNoticeInWishlist(noticeId);
}}
>
<Ionicons
name={isInWishlist ? "heart" : "heart-outline"}
size={24}
color={"primary-heading-500"}
/>
</Pressable>
</Box>
</VStack>
</Card>
</Pressable>
</Link>
);
}
return (
<Link href={`/notice/${noticeId}`} asChild>
<Pressable className="flex-1">
<Card className="p-0 rounded-lg max-w-[460px] flex-1">
{isLoading ? (
<Box className="h-auto w-full rounded-md aspect-[1/1] bg-gray-100 items-center justify-center">
<ActivityIndicator size="large" color="#3b82f6" />
</Box>
) : (
<Image
source={{
uri: image,
}}
className="h-auto w-full rounded-md aspect-[1/1]"
alt="image"
resizeMode="cover"
/>
)}
<VStack className="p-2">
<Text className="text-sm font-normal mb-2 text-typography-700">
{notice.title}
</Text>
<Box className="flex-row items-center">
<Heading size="md" className="flex-1">
{notice.price}
</Heading>
<Pressable
onPress={() => {
toggleNoticeInWishlist(noticeId);
}}
>
<Ionicons
name={isInWishlist ? "heart" : "heart-outline"}
size={24}
color={"primary-heading-500"}
/>
</Pressable>
</Box>
</VStack>
</Card>
</Pressable>
</Link>
);
}