add Zustand and del unnecessary files

This commit is contained in:
Patryk
2025-05-15 00:06:38 +02:00
parent c0b8df55a6
commit 1a8144aee4
10 changed files with 295 additions and 248 deletions

20
App.js
View File

@@ -1,20 +0,0 @@
// import { StatusBar } from 'expo-status-bar';
// import { StyleSheet, Text, View } from 'react-native';
// export default function App() {
// return (
// <View style={styles.container}>
// <Text>Open up App.js to start working on your app!</Text>
// <StatusBar style="auto" />
// </View>
// );
// }
// const styles = StyleSheet.create({
// container: {
// flex: 1,
// backgroundColor: '#fff',
// alignItems: 'center',
// justifyContent: 'center',
// },
// });

View File

@@ -3,71 +3,73 @@ import axios from "axios";
const API_URL = "https://hopp.zikor.pl";
export async function listLocations() {
try {
const response = await axios.get(`${API_URL}/locations/all`);
if (!response) {
throw new Error("No locations found");
}
return response.data;
} catch (error) {
console.error("Error fetching locations:", error);
throw error;
try {
const response = await axios.get(`${API_URL}/locations/all`);
if (!response) {
throw new Error("No locations found");
}
return response.data;
} catch (error) {
console.error("Error fetching locations:", error);
throw error;
}
}
export async function getLocation(id) {
try {
const location = await axios.get(`${API_URL}/locations/${id}`);
if (!location) {
throw new Error("Location not found");
}
return location.data;
} catch (error) {
console.error("Error fetching location:", error);
throw error;
try {
const location = await axios.get(`${API_URL}/locations/${id}`);
if (!location) {
throw new Error("Location not found");
}
return location.data;
} catch (error) {
console.error("Error fetching location:", error);
throw error;
}
}
export async function addLocation(location) {
try {
const response = await axios.post(`${API_URL}/locations/add`, location, {
headers: {
"Content-Type": "application/json",
}
});
if (!response) {
throw new Error("Failed to add location");
}
return response.data;
} catch (error) {
console.error("Error adding location:", error);
throw error;
try {
const response = await axios.post(`${API_URL}/locations/add`, location, {
headers: {
"Content-Type": "application/json",
},
});
if (!response) {
throw new Error("Failed to add location");
}
return response.data;
} catch (error) {
console.error("Error adding location:", error);
throw error;
}
}
export async function updateLocation(id, location) {
try {
const response = await axios.put(`${API_URL}/locations/${id}`, location, { headers: { "Content-Type": "application/json" } });
if (!response) {
throw new Error("Failed to add location");
}
return response.data;
} catch (error) {
console.error("Error while updating location:", error);
throw error;
try {
const response = await axios.put(`${API_URL}/locations/${id}`, location, {
headers: { "Content-Type": "application/json" },
});
if (!response) {
throw new Error("Failed to add location");
}
return response.data;
} catch (error) {
console.error("Error while updating location:", error);
throw error;
}
}
export async function deleteLocation(id) {
try {
const response = await axios.delete(`${API_URL}/locations/${id}`);
if (!response) {
throw new Error("Failed to delete location");
}
return response.data;
} catch (error) {
console.error("Error while deleting location:", error);
throw error;
try {
const response = await axios.delete(`${API_URL}/locations/${id}`);
if (!response) {
throw new Error("Failed to delete location");
}
}
return response.data;
} catch (error) {
console.error("Error while deleting location:", error);
throw error;
}
}

View File

@@ -6,7 +6,7 @@ import {
ScrollView,
} from "react-native";
import { TextInput, Button, Snackbar } from "react-native-paper";
import { addLocation } from "@/api/locations";
import useLocationStore from "@/locationStore";
export default function FormScreen() {
const [formData, setFormData] = useState({
@@ -19,7 +19,9 @@ export default function FormScreen() {
const [message, setMessage] = useState("");
const [visible, setVisible] = useState(false);
const handleAddLocation = () => {
const addLocation = useLocationStore((state) => state.addLocation);
const handleAddLocation = async () => {
if (
formData.name &&
formData.description &&
@@ -36,8 +38,7 @@ export default function FormScreen() {
population: parseInt(formData.population),
};
addLocation(newLocation);
const added = await addLocation(newLocation);
setFormData({
name: "",
description: "",
@@ -45,7 +46,7 @@ export default function FormScreen() {
area: 0,
population: 0,
});
if(addLocation != null) {
if (added != null) {
setMessage("Lokalizacja została dodana!");
setVisible(true);
} else {

View File

@@ -1,56 +1,36 @@
import { View, StyleSheet, FlatList, ActivityIndicator, RefreshControl } from 'react-native';
import { useTheme, Card, Text, Button } from 'react-native-paper';
import { Link } from 'expo-router';
import { useState, useEffect } from 'react';
import { listLocations } from '@/api/locations';
import {
View,
StyleSheet,
FlatList,
ActivityIndicator,
RefreshControl,
} from "react-native";
import { useTheme, Card, Text, Button } from "react-native-paper";
import { Link } from "expo-router";
import { useState, useEffect } from "react";
import useLocationStore from "@/locationStore";
export default function Index() {
const theme = useTheme();
const [locations, setLocations] = useState([]);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const fetchLocations = async () => {
try {
const data = await listLocations();
setLocations(data);
} catch (error) {
console.error("Error fetching locations:", error);
} finally {
setLoading(false);
}
};
const onRefresh = async () => {
setRefreshing(true);
await fetchLocations();
setRefreshing(false);
};
useEffect(() => {
fetchLocations();
}, []);
if (loading) {
return (
<View style={[styles.container, { backgroundColor: theme.colors.background }]}>
<ActivityIndicator size="large" color={theme.colors.primary} />
</View>
);
}
const { locations } = useLocationStore();
return (
<View style={[styles.container, { backgroundColor: theme.colors.background }]}>
<View
style={[styles.container, { backgroundColor: theme.colors.background }]}
>
<FlatList
data={locations}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<Card style={{ margin: 10 }}>
<Card.Cover style={{ marginBottom: 10 }} source={{ uri: item.image }} />
<Card.Cover
style={{ marginBottom: 10 }}
source={{ uri: item.image }}
/>
<Card.Content style={{ marginBottom: 10 }}>
<Text variant="titleLarge">{item.name}</Text>
<Text variant="bodyMedium">
{item.description && item.description.split('.')[0]}...
{item.description && item.description.split(".")[0]}...
</Text>
</Card.Content>
<Card.Actions>
@@ -60,14 +40,6 @@ export default function Index() {
</Card.Actions>
</Card>
)}
refreshControl={
<RefreshControl
refreshing={refreshing || loading}
onRefresh={onRefresh}
colors={["#3b82f6"]}
tintColor="#3b82f6"
/>
}
/>
</View>
);
@@ -76,8 +48,8 @@ export default function Index() {
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#25292e',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: "#25292e",
justifyContent: "center",
alignItems: "center",
},
});
});

View File

@@ -1,33 +1,42 @@
import { Link, Stack, useRouter } from 'expo-router';
import { useColorScheme } from 'react-native';
import { PaperProvider } from 'react-native-paper';
import { MD3LightTheme, MD3DarkTheme } from 'react-native-paper';
import Ionicons from '@expo/vector-icons/Ionicons';
import { deleteLocation } from '@/api/locations';
import { Link, Stack, useRouter } from "expo-router";
import { useColorScheme } from "react-native";
import { PaperProvider } from "react-native-paper";
import { MD3LightTheme, MD3DarkTheme } from "react-native-paper";
import { useEffect } from "react";
import Ionicons from "@expo/vector-icons/Ionicons";
import useLocationStore from "@/locationStore";
export default function RootLayout() {
const colorScheme = useColorScheme();
const theme = colorScheme === 'dark' ? MD3DarkTheme :
MD3LightTheme;
const theme = colorScheme === "dark" ? MD3DarkTheme : MD3LightTheme;
const router = useRouter();
const fetchLocations = useLocationStore((state) => state.fetchLocations);
const handleDelete = (id) => {
deleteLocation(id);
while (router.canGoBack()) {
router.back();
useEffect(() => {
fetchLocations();
}, []);
console.log();
const deleteLocation = useLocationStore((state) => state.deleteLocation);
const handleDelete = async (id) => {
const isDeleted = await deleteLocation(id);
if (isDeleted) {
router.replace("/");
}
router.replace('/');
};
return (
<PaperProvider theme={theme} >
<Stack screenOptions={{
headerStyle: {
backgroundColor: theme.colors.primaryContainer,
borderBottomWidth: 0
},
headerTintColor: theme.colors.primary,
}}>
<PaperProvider theme={theme}>
<Stack
screenOptions={{
headerStyle: {
backgroundColor: theme.colors.primaryContainer,
borderBottomWidth: 0,
},
headerTintColor: theme.colors.primary,
}}
>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen
name="location/[id]"
@@ -40,18 +49,28 @@ export default function RootLayout() {
asChild
style={{ marginRight: 11 }}
>
<Ionicons name="pencil" color={theme.colors.primary} size={24} />
<Ionicons
name="pencil"
color={theme.colors.primary}
size={24}
/>
</Link>
),
})}
/>
<Stack.Screen name="location/edit/[id]" options={({ route }) => ({
title: "Edycja",
headerRight: () => (
<Ionicons name="trash-bin" color={theme.colors.primary} size={24} onPress={() => handleDelete(route.params.id)} />
),
})}
<Stack.Screen
name="location/edit/[id]"
options={({ route }) => ({
title: "Edycja",
headerRight: () => (
<Ionicons
name="trash-bin"
color={theme.colors.primary}
size={24}
onPress={() => handleDelete(route.params.id)}
/>
),
})}
/>
</Stack>
</PaperProvider>

View File

@@ -1,38 +1,25 @@
import { View, ScrollView, StyleSheet, ActivityIndicator } from 'react-native';
import { useTheme, Text, Card } from 'react-native-paper';
import { useLocalSearchParams } from 'expo-router';
import { useEffect, useState } from 'react';
import { getLocation } from '@/api/locations';
import { View, ScrollView, StyleSheet, ActivityIndicator } from "react-native";
import { useEffect } from "react";
import { useTheme, Text, Card } from "react-native-paper";
import { useLocalSearchParams } from "expo-router";
import useLocationStore from "@/locationStore";
export default function Location() {
const theme = useTheme();
const { id } = useLocalSearchParams();
const [location, setLocation] = useState(null);
const [loading, setLoading] = useState(true);
const getLocation = useLocationStore((state) => state.getLocation);
const fetchLocations = useLocationStore((state) => state.fetchLocations);
const loading = useLocationStore((state) => state.loading);
const location = getLocation(id);
useEffect(() => {
const fetchLocation = async () => {
try {
const data = await getLocation(id)
setLocation(data);
} catch (error) {
console.error("Error fetching location:", error);
} finally {
setLoading(false);
}
if (!location && !loading) {
fetchLocations();
}
fetchLocation();
}, [id]);
}, [location, loading, fetchLocations]);
if (loading) {
return (
<View style={[styles.container, { backgroundColor: theme.colors.background }]}>
<ActivityIndicator size="large" color={theme.colors.primary} />
</View>
);
}
if (!location) {
if (loading || !location) {
return (
<View style={styles.container}>
<Text style={styles.text}>Brak lokalizacji - {id}</Text>
@@ -44,7 +31,10 @@ export default function Location() {
<View style={styles.container}>
<ScrollView>
<Card style={{ margin: 10 }}>
<Card.Cover style={{ marginBottom: 10 }} source={{ uri: location.image }} />
<Card.Cover
style={{ marginBottom: 10 }}
source={{ uri: location.image }}
/>
<Card.Content style={{ marginBottom: 10 }}>
<Text variant="headlineLarge" style={{ marginBottom: 10 }}>
{location.name}
@@ -75,11 +65,11 @@ export default function Location() {
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#25292e',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: "#25292e",
justifyContent: "center",
alignItems: "center",
},
text: {
color: '#fff',
color: "#fff",
},
});
});

View File

@@ -1,8 +1,16 @@
import { useState, useEffect } from 'react';
import { StyleSheet, Platform, ScrollView, KeyboardAvoidingView, View, ActivityIndicator } from 'react-native';
import { TextInput, Button, Snackbar, useTheme } from 'react-native-paper';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { getLocation, updateLocation } from '@/api/locations';
import { useState, useEffect } from "react";
import {
StyleSheet,
Platform,
ScrollView,
KeyboardAvoidingView,
View,
ActivityIndicator,
} from "react-native";
import { TextInput, Button, Snackbar, useTheme } from "react-native-paper";
import { useLocalSearchParams, useRouter } from "expo-router";
// import { getLocation } from "@/api/locations";
import useLocationStore from "@/locationStore";
export default function EditLocation() {
const theme = useTheme();
@@ -10,40 +18,34 @@ export default function EditLocation() {
const router = useRouter();
const [loading, setLoading] = useState(true);
const [formData, setFormData] = useState({
name: '',
description: '',
image: '',
area: '',
population: '',
name: "",
description: "",
image: "",
area: "",
population: "",
});
const [message, setMessage] = useState('');
const [message, setMessage] = useState("");
const [visible, setVisible] = useState(false);
const updateLocation = useLocationStore((state) => state.updateLocation);
const getLocation = useLocationStore((state) => state.getLocation);
useEffect(() => {
const fetchLocation = async () => {
try {
const data = await getLocation(id)
if (data) {
setFormData({
name: data.name,
description: data.description,
image: data.image,
area: data.area.toString(),
population: data.population.toString(),
});
}
} catch (error) {
console.error("Error fetching location:", error);
} finally {
setLoading(false);
}
const data = getLocation(id);
if (data) {
setFormData({
name: data.name,
description: data.description,
image: data.image,
area: data.area.toString(),
population: data.population.toString(),
});
}
fetchLocation();
}, [id]);
setLoading(false);
}, [id, getLocation]);
const handleEditLocation = () => {
const handleEditLocation = async () => {
if (
formData.name &&
formData.description &&
@@ -51,7 +53,8 @@ export default function EditLocation() {
formData.area &&
formData.population
) {
const response = updateLocation(id, {
// console.log("Form data:", formData);
const response = await updateLocation(id, {
name: formData.name,
description: formData.description,
image: formData.image,
@@ -60,25 +63,30 @@ export default function EditLocation() {
});
if (response) {
setMessage('Lokalizacja została zaktualizowana!');
setMessage("Lokalizacja została zaktualizowana!");
setVisible(true);
while (router.canGoBack()) { // Pop from stack until one element is left
router.back();
}
router.replace("/"); // Replace the last remaining stack element
// while (router.canGoBack()) {
// Pop from stack until one element is left
// router.back();
// }
setTimeout(() => {
router.replace("/");
}, 300); // Replace the last remaining stack element
} else {
setMessage('Wystąpił błąd podczas aktualizacji lokalizacji!');
setMessage("Wystąpił błąd podczas aktualizacji lokalizacji!");
setVisible(true);
}
} else {
setMessage('Wypełnij wszystkie pola!');
setMessage("Wypełnij wszystkie pola!");
setVisible(true);
}
};
if (loading) {
return (
<View style={[styles.container, { backgroundColor: theme.colors.background }]}>
<View
style={[styles.container, { backgroundColor: theme.colors.background }]}
>
<ActivityIndicator size="large" color={theme.colors.primary} />
</View>
);
@@ -87,7 +95,7 @@ export default function EditLocation() {
return (
<KeyboardAvoidingView
style={{ flex: 1 }}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
behavior={Platform.OS === "ios" ? "padding" : "height"}
>
<ScrollView contentContainerStyle={styles.container}>
<Snackbar
@@ -101,7 +109,7 @@ export default function EditLocation() {
mode="outlined"
label="Nazwa"
placeholder="Wpisz nazwę"
style={{ margin: 10, width: '100%' }}
style={{ margin: 10, width: "100%" }}
value={formData.name}
onChangeText={(e) => setFormData({ ...formData, name: e })}
/>
@@ -109,7 +117,7 @@ export default function EditLocation() {
mode="outlined"
label="Opis"
placeholder="Wpisz opis"
style={{ margin: 10, width: '100%' }}
style={{ margin: 10, width: "100%" }}
multiline={true}
value={formData.description}
onChangeText={(e) => setFormData({ ...formData, description: e })}
@@ -119,7 +127,7 @@ export default function EditLocation() {
label="Link do zdjęcia"
multiline={true}
placeholder="Wpisz link do zdjęcia"
style={{ margin: 10, width: '100%' }}
style={{ margin: 10, width: "100%" }}
value={formData.image}
onChangeText={(e) => setFormData({ ...formData, image: e })}
/>
@@ -127,7 +135,7 @@ export default function EditLocation() {
mode="outlined"
label="Powierzchnia"
placeholder="Wpisz powierzchnię"
style={{ margin: 10, width: '100%' }}
style={{ margin: 10, width: "100%" }}
value={formData.area}
keyboardType="numeric"
onChangeText={(e) => setFormData({ ...formData, area: e })}
@@ -136,15 +144,15 @@ export default function EditLocation() {
mode="outlined"
label="Ludność"
placeholder="Wpisz liczbę ludności"
style={{ margin: 10, width: '100%' }}
style={{ margin: 10, width: "100%" }}
value={formData.population}
keyboardType="numeric"
onChangeText={(e) => setFormData({ ...formData, population: e })}
/>
<Button
style={{ margin: 10, width: '100%' }}
style={{ margin: 10, width: "100%" }}
icon="plus-circle-outline"
mode={'contained'}
mode={"contained"}
onPress={handleEditLocation}
>
Edytuj
@@ -157,8 +165,8 @@ export default function EditLocation() {
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#25292e',
justifyContent: 'flex-start',
alignItems: 'center',
backgroundColor: "#25292e",
justifyContent: "flex-start",
alignItems: "center",
},
});
});

75
locationStore.js Normal file
View File

@@ -0,0 +1,75 @@
import { create } from "zustand";
import * as api from "@/api/locations";
const useLocationStore = create((set, get) => ({
locations: [],
loading: false,
error: null,
fetchLocations: async () => {
set({ loading: true, error: null });
try {
const data = await api.listLocations();
set({ locations: data, loading: false });
} catch (error) {
set({ error, loading: false });
}
},
addLocation: async (location) => {
set({ loading: true, error: null });
try {
const newLoc = await api.addLocation(location);
set((state) => ({
locations: [...state.locations, newLoc],
loading: false,
}));
return newLoc;
} catch (error) {
set({ error, loading: false });
return null;
}
},
updateLocation: async (id, location) => {
set({ loading: true, error: null });
try {
const updated = await api.updateLocation(id, location);
set((state) => ({
locations: state.locations.map((loc) =>
loc.id == id ? updated : loc
),
loading: false,
}));
return updated;
} catch (error) {
set({ error, loading: false });
return null;
}
},
deleteLocation: async (id) => {
set({ loading: true, error: null });
try {
const deleted = await api.deleteLocation(id);
set((state) => ({
locations: state.locations.filter((loc) => loc.id != id),
loading: false,
}));
if(deleted) {
return true;
}
} catch (error) {
set({ error, loading: false });
return false;
}
},
getLocation: (id) => {
return get().locations.find((loc) => String(loc.id) === String(id));
},
}));
export default useLocationStore;

8
package-lock.json generated
View File

@@ -13,7 +13,7 @@
"expo": "^53.0.0",
"expo-constants": "~17.1.6",
"expo-linking": "~7.1.4",
"expo-router": "~5.0.6",
"expo-router": "~5.0.7",
"expo-status-bar": "~2.2.3",
"react": "19.0.0",
"react-dom": "19.0.0",
@@ -4457,9 +4457,9 @@
}
},
"node_modules/expo-router": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/expo-router/-/expo-router-5.0.6.tgz",
"integrity": "sha512-/44G3liB7LMMDoUO+lN5TS8XvZrAhLtq7cVGoilO2QkoSBjFQfxFA9VYOVWVlu2R80tN6dM3cgsEuoA275FGQg==",
"version": "5.0.7",
"resolved": "https://registry.npmjs.org/expo-router/-/expo-router-5.0.7.tgz",
"integrity": "sha512-NlEgRXCKtseDuIHBp87UfkvqsuVrc0MYG+zg33dopaN6wik4RkrWWxUYdNPHub0s/7qMye6zZBY4ZCrXwd/xpA==",
"license": "MIT",
"dependencies": {
"@expo/metro-runtime": "5.0.4",

View File

@@ -14,7 +14,7 @@
"expo": "^53.0.0",
"expo-constants": "~17.1.6",
"expo-linking": "~7.1.4",
"expo-router": "~5.0.6",
"expo-router": "~5.0.7",
"expo-status-bar": "~2.2.3",
"react": "19.0.0",
"react-dom": "19.0.0",