zdjęcia pobierają się na głównej stronie + naprawiono kilka innych bugów.

takich jak wyświetlanie "Moich ogłoszeń nie dla poprawnego id etc."
This commit is contained in:
2025-06-08 22:31:52 +02:00
parent bcce392c9b
commit 2218c5eb33
8 changed files with 172 additions and 164 deletions

View File

@@ -8,7 +8,7 @@ export async function listCategories() {
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
try { try {
const response = await axios.get(`${API_URL}/vars/categories`, { headers }); const response = await axios.get(`${API_URL}/vars/categories`, { headers: headers });
return response.data; return response.data;
} catch (err) { } catch (err) {
console.error("Nie udało się pobrać listy kategorii.", err.response.status); console.error("Nie udało się pobrać listy kategorii.", err.response.status);

View File

@@ -33,12 +33,10 @@ export async function getNoticeById(noticeId) {
} }
export async function createNotice(notice) { export async function createNotice(notice) {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
try { try {
const response = await axios.post(`${API_URL}/notices/add`, notice, { const response = await axios.post(`${API_URL}/notices/add`, notice, {headers: headers});
headers: {
"Content-Type": "application/json",
},
});
if (response.data.noticeId !== null) { if (response.data.noticeId !== null) {
for (const imageUri of notice.image) { for (const imageUri of notice.image) {
@@ -73,27 +71,26 @@ export async function getAllImagesByNoticeId(noticeId) {
const { token } = useAuthStore.getState(); const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
try { try {
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`, { const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`, {headers: headers});
headers,
});
if (listResponse.data && listResponse.data.length > 0) { if (listResponse.data && listResponse.data.length > 0) {
return listResponse.data.map( return listResponse.data.map((imageName) => ({
(imageName) => `${API_URL}/images/get/${imageName}` uri: `${API_URL}/images/get/${imageName}`,
); headers: headers,
}));
} }
return ["https://http.cat/404.jpg"]; return [{ uri: "https://http.cat/404.jpg" }];
} catch (err) { } catch (err) {
if (err.response.status === 404) { if (err.response.status === 404) {
// console.info(`Ogłoszenie o id: ${noticeId} nie posiada zdjęć.`); // console.info(`Ogłoszenie o id: ${noticeId} nie posiada zdjęć.`);
return ["https://http.cat/404.jpg"]; return [{ uri: "https://http.cat/404.jpg" }];
} }
console.warn( console.warn(
`Nie udało się pobrać listy zdjęć dla ogłoszenia o id: ${noticeId}`, `Nie udało się pobrać listy zdjęć dla ogłoszenia o id: ${noticeId}`,
err err
); );
return ["https://http.cat/404.jpg"]; return [{ uri: "https://http.cat/404.jpg" }];
} }
} }

View File

@@ -1,6 +1,5 @@
import axios from "axios"; import axios from "axios";
import { useAuthStore } from "@/store/authStore"; import { useAuthStore } from "@/store/authStore";
// import FormData from 'form-data'
const API_URL = "https://hopp.zikor.pl/api/v1/wishlist"; const API_URL = "https://hopp.zikor.pl/api/v1/wishlist";
@@ -36,3 +35,4 @@ export async function getWishlist() {
throw error; throw error;
} }
} }
``

View File

@@ -1,6 +1,6 @@
import { useNoticesStore } from "@/store/noticesStore"; import { useNoticesStore } from "@/store/noticesStore";
import { NoticeCard } from "@/components/NoticeCard"; import { NoticeCard } from "@/components/NoticeCard";
import { Button, ButtonIcon, ButtonText } from "@/components/ui/button"; import { Button, ButtonText } from "@/components/ui/button";
import { Box } from "@/components/ui/box"; import { Box } from "@/components/ui/box";
import { Text } from "@/components/ui/text"; import { Text } from "@/components/ui/text";
@@ -12,15 +12,17 @@ import { Linking } from "react-native";
import { Ionicons } from "@expo/vector-icons"; import { Ionicons } from "@expo/vector-icons";
import { useToast, Toast, ToastTitle } from "@/components/ui/toast"; import { useToast, Toast, ToastTitle } from "@/components/ui/toast";
import { AppState } from "react-native"; import { AppState } from "react-native";
import { useAuthStore } from "@/store/authStore";
export default function UserNotices() { export default function UserNotices() {
const { notices, fetchNotices, deleteNotice } = useNoticesStore(); const { notices, fetchNotices, deleteNotice } = useNoticesStore();
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [isRedirecting, setIsRedirecting] = useState(false); const [isRedirecting, setIsRedirecting] = useState(false);
const currentUserId = 1;
const toast = useToast(); const toast = useToast();
const appState = useRef(AppState.currentState); const appState = useRef(AppState.currentState);
const [toastId, setToastId] = useState(0); const [toastId, setToastId] = useState(0);
const { user_id } = useAuthStore.getState();
const currentUserId= user_id;
useEffect(() => { useEffect(() => {
if (!isRedirecting) return; if (!isRedirecting) return;
@@ -28,9 +30,9 @@ export default function UserNotices() {
if (state === "active") { if (state === "active") {
setIsRedirecting(false); setIsRedirecting(false);
const paymentStatus = "CORRECT"; const paymentStatus = "CORRECT";
if (paymentStatus == "INCORRECT") { if (paymentStatus === "INCORRECT") {
showNewToast("Płatność została anulowana."); showNewToast("Płatność została anulowana.");
} else if (paymentStatus == "CORRECT") { } else if (paymentStatus === "CORRECT") {
showNewToast("Płatność została zrealizowana."); showNewToast("Płatność została zrealizowana.");
} else { } else {
showNewToast("Płatność jeszcze nie wpłynęła."); showNewToast("Płatność jeszcze nie wpłynęła.");
@@ -83,7 +85,7 @@ export default function UserNotices() {
const paymentResult = await createPayment(); //trzeba dodać orderId const paymentResult = await createPayment(); //trzeba dodać orderId
if (paymentResult) { if (paymentResult) {
setIsRedirecting(true); setIsRedirecting(true);
Linking.openURL(paymentResult); await Linking.openURL(paymentResult);
setWaitingForPayment(true); setWaitingForPayment(true);
} else { } else {
console.log(`Nie udało się aktywować ogłoszenia ${noticeId}.`); console.log(`Nie udało się aktywować ogłoszenia ${noticeId}.`);

View File

@@ -1,4 +1,4 @@
import { ScrollView, View } from "react-native"; import { ScrollView } from "react-native";
import { useNoticesStore } from "@/store/noticesStore"; import { useNoticesStore } from "@/store/noticesStore";
import { CategorySection } from "@/components/CategorySection"; import { CategorySection } from "@/components/CategorySection";
import { NoticeSection } from "@/components/NoticeSection"; import { NoticeSection } from "@/components/NoticeSection";
@@ -10,7 +10,7 @@ import { useEffect, useState } from "react";
import { SafeAreaView } from "react-native"; import { SafeAreaView } from "react-native";
export default function Home() { export default function Home() {
const token = useAuthStore((state) => state.token); const { token } = useAuthStore.getState();
const router = useRouter(); const router = useRouter();
const [isReady, setIsReady] = useState(false); const [isReady, setIsReady] = useState(false);
const fetchNotices = useNoticesStore((state) => state.fetchNotices); const fetchNotices = useNoticesStore((state) => state.fetchNotices);
@@ -35,7 +35,7 @@ export default function Home() {
// console.log("Notices:", notices); // console.log("Notices:", notices);
// console.log("Notices length:", notices.length); // console.log("Notices length:", notices.length);
const activeNotices = notices.filter((notice) => notice.status == "ACTIVE"); const activeNotices = notices.filter((notice) => notice.status === "ACTIVE");
// console.log("Activer Notices:", activeNotices.length); // console.log("Activer Notices:", activeNotices.length);
const latestNotices = [...activeNotices] const latestNotices = [...activeNotices]
.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate)) .sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate))

View File

@@ -4,25 +4,36 @@ import { NoticeCard } from "@/components/NoticeCard";
import { Ionicons } from "@expo/vector-icons"; import { Ionicons } from "@expo/vector-icons";
import { Box } from "@/components/ui/box"; import { Box } from "@/components/ui/box";
import { Text } from "@/components/ui/text"; import { Text } from "@/components/ui/text";
import { useEffect } from "react"; import {useCallback} from "react";
import { useFocusEffect } from "@react-navigation/native";
export default function Wishlist() { export default function Wishlist() {
const wishlistNotices = useWishlist((state) => state.wishlistNotices); const wishlistNotices = useWishlist((state) => state.wishlistNotices);
const fetchWishlist = useWishlist((state) => state.fetchWishlist); const fetchWishlist = useWishlist((state) => state.fetchWishlist);
useEffect(() => { useFocusEffect(
fetchWishlist(); useCallback(() => {
}, []); fetchWishlist();
}, [fetchWishlist])
);
const styles = {
container: {
margin: 10,
}
}
// console.log("Wishlist notices:", wishlistNotices); // console.log("Wishlist notices:", wishlistNotices);
if (wishlistNotices.length === 0) { if (wishlistNotices.length === 0) {
return ( return (
<Box className="flex-row flex-1 justify-center"> <Box style={styles.container} className="flex-row flex-1 justify-center">
<Ionicons name="sad-outline" size={24} color="black" /> <Ionicons name="sad-outline" size={24} color="black" />
<Text>Brak ulubionych ogłoszeń</Text> <Text>Brak ulubionych ogłoszeń</Text>
</Box> </Box>
); );
} }
return ( return (
<FlatList <FlatList
data={wishlistNotices} data={wishlistNotices}
@@ -30,7 +41,6 @@ export default function Wishlist() {
numColumns={2} numColumns={2}
columnContainerClassName="m-2" columnContainerClassName="m-2"
columnWrapperClassName="gap-2 m-2" columnWrapperClassName="gap-2 m-2"
k
renderItem={({ item }) => <NoticeCard notice={item} />} renderItem={({ item }) => <NoticeCard notice={item} />}
/> />
); );

View File

@@ -34,7 +34,7 @@ export function NoticeCard({ notice }) {
const fetchImage = async () => { const fetchImage = async () => {
if (!noticeId) { if (!noticeId) {
if (isMounted) { if (isMounted) {
setImage("https://http.cat/404.jpg"); setImage({uri: "https://http.cat/404.jpg"});
setIsLoading(false); setIsLoading(false);
} }
return; return;
@@ -45,13 +45,13 @@ export function NoticeCard({ notice }) {
const images = await getAllImagesByNoticeId(noticeId); const images = await getAllImagesByNoticeId(noticeId);
if (isMounted) { if (isMounted) {
setImage( setImage(
images && images.length > 0 ? images[0] : "https://http.cat/404.jpg" images && images.length > 0 ? images[0] : {uri: "https://http.cat/404.jpg"}
); );
} }
} catch (error) { } catch (error) {
console.error(`Error while loading image: ${error}`); console.error(`Error while loading image: ${error}`);
if (isMounted) { if (isMounted) {
setImage("https://http.cat/404.jpg"); setImage({uri: "https://http.cat/404.jpg"});
} }
} finally { } finally {
if (isMounted) { if (isMounted) {
@@ -81,9 +81,7 @@ export function NoticeCard({ notice }) {
</Box> </Box>
) : ( ) : (
<Image <Image
source={{ source={image}
uri: image,
}}
className="h-auto w-full rounded-md aspect-[1/1]" className="h-auto w-full rounded-md aspect-[1/1]"
alt="image" alt="image"
resizeMode="cover" resizeMode="cover"

View File

@@ -1,141 +1,142 @@
import { create } from "zustand"; import {create} from "zustand";
import { createJSONStorage, persist } from "zustand/middleware"; import {createJSONStorage, persist} from "zustand/middleware";
import AsyncStorage from "@react-native-async-storage/async-storage"; import AsyncStorage from "@react-native-async-storage/async-storage";
import axios from "axios"; import axios from "axios";
const API_URL = "https://hopp.zikor.pl/api/v1"; const API_URL = "https://hopp.zikor.pl/api/v1";
let interceptorInitialized = false;
export const useAuthStore = create( export const useAuthStore = create(
persist( persist(
(set, get) => { (set, get) => {
// Dodaj interceptor tylko raz if (!interceptorInitialized.current) {
if (!axios.interceptors.response.handlers.length) { axios.interceptors.response.use(
axios.interceptors.response.use( (response) => response,
(response) => response, (error) => {
(error) => { if (
if ( (error.response && error.response.status === 401) ||
(error.response && error.response.status === 401) || error.response.status === 403
error.response.status === 403 ) {
) { set({user_id: null, token: null, isLoading: false});
set({ user: null, token: null, isLoading: false }); delete axios.defaults.headers.common["Authorization"];
delete axios.defaults.headers.common["Authorization"]; }
return Promise.reject(error);
}
);
interceptorInitialized = true;
} }
return Promise.reject(error); return {
} user_id: null,
); token: null,
} isLoading: false,
error: null,
return { signIn: async (email, password) => {
user_id: null, set({isLoading: true, error: null});
token: null, try {
isLoading: false, const response = await axios.post(`${API_URL}/auth/login`, {
error: null, email,
password,
});
signIn: async (email, password) => { const user_id = response.data.user_id;
set({ isLoading: true, error: null }); const token = response.data.token;
try { set({user_id: user_id, token: token, isLoading: false});
const response = await axios.post(`${API_URL}/auth/login`, {
email,
password,
});
const user_id = response.data.user_id; axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
const token = response.data.token; } catch (error) {
set({ user_id: user_id, token: token, isLoading: false }); set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; signUp: async (userData) => {
} catch (error) { set({isLoading: true, error: null});
set({ try {
error: error.response?.data?.message || error.message, const response = await axios.post(
isLoading: false, `${API_URL}/auth/register`,
}); userData,
throw error; {
} headers: {"Content-Type": "application/json"},
}
);
const user_id = response.data.user_id;
const token = response.data.token;
set({user_id: user_id, token: token, isLoading: false});
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) {
set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
signInWithGoogle: async (googleToken) => {
set({isLoading: true, error: null});
try {
const response = await axios.post(
`${API_URL}/auth/google`,
{googleToken: googleToken},
{
headers: {"Content-Type": "application/json"},
}
);
const user_id = response.data.user_id;
const token = response.data.token;
set({user_id: user_id, token: token, isLoading: false});
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) {
set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
signOut: async () => {
try {
await axios.post(`${API_URL}/auth/logout`);
} catch (error) {
console.error("Logout error:", error);
} finally {
delete axios.defaults.headers.common["Authorization"];
set({user_id: null, token: null});
}
},
// checkAuth: async () => {
// const { token } = useAuthStore.getState();
// if (!token) return null;
// set({ isLoading: true });
// try {
// axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
// const response = await axios.get(`${API_URL}/auth/me`);
// set({ user_id: response.data, isLoading: false });
// return response.data;
// } catch (error) {
// delete axios.defaults.headers.common["Authorization"];
// set({ user_id: null, token: null, isLoading: false });
// return null;
// }
// },
};
}, },
{
signUp: async (userData) => { name: "auth-storage",
set({ isLoading: true, error: null }); storage: createJSONStorage(() => AsyncStorage),
try { }
const response = await axios.post( )
`${API_URL}/auth/register`,
userData,
{
headers: { "Content-Type": "application/json" },
}
);
const user_id = response.data.user_id;
const token = response.data.token;
set({ user_id: user_id, token: token, isLoading: false });
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) {
set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
signInWithGoogle: async (googleToken) => {
set({ isLoading: true, error: null });
try {
const response = await axios.post(
`${API_URL}/auth/google`,
{ googleToken: googleToken },
{
headers: { "Content-Type": "application/json" },
}
);
const user_id = response.data.user_id;
const token = response.data.token;
set({ user_id: user_id, token: token, isLoading: false });
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) {
set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
signOut: async () => {
try {
await axios.post(`${API_URL}/auth/logout`);
} catch (error) {
console.error("Logout error:", error);
} finally {
delete axios.defaults.headers.common["Authorization"];
set({ user_id: null, token: null });
}
},
// checkAuth: async () => {
// const { token } = useAuthStore.getState();
// if (!token) return null;
// set({ isLoading: true });
// try {
// axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
// const response = await axios.get(`${API_URL}/auth/me`);
// set({ user_id: response.data, isLoading: false });
// return response.data;
// } catch (error) {
// delete axios.defaults.headers.common["Authorization"];
// set({ user_id: null, token: null, isLoading: false });
// return null;
// }
// },
};
},
{
name: "auth-storage",
storage: createJSONStorage(() => AsyncStorage),
}
)
); );