crud for tasks + auth

This commit is contained in:
Teodor
2026-04-20 01:05:29 +02:00
parent 0abfb47d6f
commit 473ba75e3e
13 changed files with 916 additions and 14 deletions

40
app/(tabs)/_layout.tsx Normal file
View File

@@ -0,0 +1,40 @@
import { supabase } from "@/lib/supabase";
import { Session } from "@supabase/supabase-js";
import { Redirect, Tabs } from "expo-router";
import { useEffect, useState } from "react";
export default function TabLayout() {
const [session, SetSession] = useState<Session | null>(null)
const [loading, SetLoading] = useState(true);
useEffect(() => {
const loadSession = async () => {
const { data } = await supabase.auth.getSession();
SetSession(data.session ?? null);
SetLoading(false);
}
loadSession();
const { data: sub } = supabase.auth.onAuthStateChange((_event, newSession) => {
SetSession(newSession);
SetLoading(false);
});
return () => sub.subscription.unsubscribe();
}, []);
if (loading) {
return null;
}
if (!session) {
return <Redirect href="/createUser" />;
}
return (
<Tabs>
<Tabs.Screen name="index" options={{title: "Today"}} />
<Tabs.Screen name="tasks" options={{title: "Tasks"}} />
</Tabs>
);
}

110
app/(tabs)/createTask.tsx Normal file
View File

@@ -0,0 +1,110 @@
import { defaultStyles } from '@/constants/defaultStyles';
import { supabase } from '@/lib/supabase';
import { router, Stack } from 'expo-router';
import { useState } from 'react';
import { ActivityIndicator, Alert, Button, Keyboard, KeyboardAvoidingView, Platform, Pressable, Text, TextInput, TouchableWithoutFeedback, View } from 'react-native';
export default function CreateTask() {
const [title, SetTitle] = useState('');
const [description, SetDescription] = useState('');
const [isCompleted, SetIsCompleted] = useState(false);
const [deadline, SetDeadline] = useState('');
const [isSaving, SetIsSaving] = useState(false);
const AddNote = async () => {
if(title.trim() === '' || description.trim() === '' || deadline.trim() === '') {
Alert.alert("All fields are required!");
return;
}
const { data, error: userError } = await supabase.auth.getUser();
if(userError || !data.user) {
router.replace("../createUser");
return;
}
SetIsSaving(true);
const { error: dbError } = await supabase.from("tasks").insert({
title,
description,
isCompleted,
lastChanged: new Date().toISOString(),
deadline,
uId: data.user.id,
});
if (dbError) {
Alert.alert("Task could not be created, please try again");
SetIsSaving(false);
return;
}
Alert.alert("Task successfully added!");
SetTitle('');
SetDescription('');
SetIsCompleted(false);
SetDeadline('');
SetIsSaving(false);
router.back();
}
return (
<>
<Stack.Screen
options={{
title: "Create Task",
headerTitleStyle: defaultStyles.title
}}
/>
<View style={defaultStyles.container}>
<Text style={defaultStyles.title}>Create New Task</Text>
<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === "ios" ? "padding" : "height"}>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={defaultStyles.container}>
<TextInput
style={defaultStyles.inputText}
placeholder="Enter title"
value={title}
onChangeText={SetTitle}
/>
<TextInput
style={defaultStyles.inputText}
placeholder="Enter description"
value={description}
onChangeText={SetDescription}
/>
<TextInput
style={defaultStyles.inputText}
placeholder="Deadline (YYYY-MM-DD)"
value={deadline}
onChangeText={SetDeadline}
/>
<Pressable
onPress={() => SetIsCompleted(state => !state)}
style={defaultStyles.checkboxContainer}
>
<View style={defaultStyles.checkbox}>
{isCompleted && <Text style={defaultStyles.checkboxMark}></Text>}
</View>
<Text style={defaultStyles.checkboxLabel}>{isCompleted ? 'Completed' : 'Not completed'}</Text>
</Pressable>
<Button title={isSaving ? "Saving..." : "Save"} onPress={AddNote} disabled={isSaving} />
{isSaving && (
<ActivityIndicator size="large" />
)}
<Button title="Cancel" onPress={() => router.back()} />
</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
</View>
</>
)
}

133
app/(tabs)/editTask.tsx Normal file
View File

@@ -0,0 +1,133 @@
import { defaultStyles } from '@/constants/defaultStyles';
import { supabase } from '@/lib/supabase';
import { router, Stack, useFocusEffect, useLocalSearchParams } from 'expo-router';
import { useCallback, useState } from 'react';
import { ActivityIndicator, Alert, Button, Keyboard, KeyboardAvoidingView, Platform, Pressable, Text, TextInput, TouchableWithoutFeedback, View } from 'react-native';
export default function EditTask() {
const [title, SetTitle] = useState('');
const [description, SetDescription] = useState('');
const [isCompleted, SetIsCompleted] = useState(false);
const [deadline, SetDeadline] = useState('');
const [isSaving, SetIsSaving] = useState(false);
const { tId } = useLocalSearchParams();
useFocusEffect(
useCallback(() => {
const GetTask = async () => {
if (!tId) return;
const { data, error } = await supabase.from("tasks").select("*").eq("tId", tId).single();
if (error) {
Alert.alert("Task not found");
return;
}
if (data) {
SetTitle(data.title);
SetDescription(data.description);
SetIsCompleted(data.isCompleted);
SetDeadline(data.deadline);
}
}
GetTask();
}, [tId])
);
const EditTask = async () => {
if(title.trim() === '' || description.trim() === '' || deadline.trim() === '') {
Alert.alert("All fields are required!");
return;
}
const { data, error: userError } = await supabase.auth.getUser();
if(userError || !data.user) {
router.replace("../createUser");
return;
}
SetIsSaving(true);
const { error: dbError } = await supabase.from("tasks").update({
title,
description,
isCompleted,
lastChanged: new Date().toISOString(),
deadline,
uId: data.user.id,
}).eq("tId", tId);
if (dbError) {
Alert.alert("Task could not be edited, please try again");
return;
}
Alert.alert("Task successfully edited!");
SetTitle('');
SetDescription('');
SetIsCompleted(false);
SetDeadline('');
SetIsSaving(false);
router.back();
}
return (
<>
<Stack.Screen
options={{
title: "Edit Task",
headerTitleStyle: defaultStyles.title
}}
/>
<View style={defaultStyles.container}>
<Text style={defaultStyles.title}>Edit Task</Text>
<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === "ios" ? "padding" : "height"}>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={defaultStyles.container}>
<TextInput
style={defaultStyles.inputText}
placeholder="Title"
value={title}
onChangeText={SetTitle}
/>
<TextInput
style={defaultStyles.inputText}
placeholder="Text"
value={description}
onChangeText={SetDescription}
/>
<TextInput
style={defaultStyles.inputText}
placeholder="Deadline (YYYY-MM-DD)"
value={deadline}
onChangeText={SetDeadline}
/>
<Pressable
onPress={() => SetIsCompleted(state => !state)}
style={defaultStyles.checkboxContainer}
>
<View style={defaultStyles.checkbox}>
{isCompleted && <Text style={defaultStyles.checkboxMark}></Text>}
</View>
<Text style={defaultStyles.checkboxLabel}>{isCompleted ? 'Completed' : 'Not completed'}</Text>
</Pressable>
<Button title={isSaving ? "Saving..." : "Save"} onPress={EditTask} disabled={isSaving} />
{isSaving && (
<ActivityIndicator size="large" />
)}
<Button title="Cancel" onPress={() => router.back()} />
</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
</View>
</>
)
}

28
app/(tabs)/index.tsx Normal file
View File

@@ -0,0 +1,28 @@
import { defaultStyles } from "@/constants/defaultStyles";
import { supabase } from "@/lib/supabase";
import { Stack } from "expo-router";
import { Button, Text, View } from "react-native";
export default function HomeScreen() {
return (
<View style={defaultStyles.container}>
<Stack.Screen
options={{
title: "Tasks",
headerTitleStyle: defaultStyles.title,
headerRight: () => {
return (
<View style={defaultStyles.buttonContainer}>
<Button title="Logout" onPress={async () => await supabase.auth.signOut()} />
</View>
)
},
}}
/>
<View style={defaultStyles.container}>
<Text style={defaultStyles.body}>Hello, World!</Text>
</View>
</View>
)
}

141
app/(tabs)/tasks.tsx Normal file
View File

@@ -0,0 +1,141 @@
import { defaultStyles } from "@/constants/defaultStyles";
import { supabase } from "@/lib/supabase";
import { Ionicons } from '@expo/vector-icons';
import { Session } from "@supabase/supabase-js";
import { router, Stack, useFocusEffect } from "expo-router";
import { useCallback, useEffect, useState } from "react";
import { Alert, Button, Pressable, SectionList, Text, View } from "react-native";
type Task = {
tId: string;
title: string;
description: string;
isCompleted: boolean;
lastChanged: string;
deadline: string;
uId: string;
}
export default function Tasks() {
const [tasks, SetTasks] = useState<Task[]>([])
const [session, SetSession] = useState<Session | null>(null)
const taskSections = [
{ title: "Upcoming Tasks", data: tasks.filter((task) => !task.isCompleted), emptyMessage: "No upcoming tasks" },
{ title: "Completed Tasks", data: tasks.filter((task) => task.isCompleted), emptyMessage: "No completed tasks" },
];
useEffect(() => {
supabase.auth.getSession().then(({ data }) => SetSession(data.session ?? null))
const { data: sub } = supabase.auth.onAuthStateChange((_event, newSession) => {
SetSession(newSession)
})
return () => sub.subscription.unsubscribe()
},
[])
useFocusEffect(
useCallback(() => {
if (session) {
GetTasks();
}
}, [session])
);
const GetTasks = async () => {
const { data, error } = await supabase.from("tasks").select("tId, title, description, isCompleted,lastChanged, deadline, uId").order("deadline", { ascending: false });
if (error) {
Alert.alert("Task could not be fetched, please try again");
return;
}
SetTasks(data ?? []);
}
const DeleteTask = async (tId: string) => {
Alert.alert(
"Delete Task",
"Are you sure you want to delete this task?",
[
{
text: "Cancel",
style: "cancel"
},
{
text: "Delete",
style: "destructive",
onPress: async () => {
const { error } = await supabase.from("tasks").delete().eq("tId", tId);
if (error) {
Alert.alert("Task could not be deleted, please try again");
return;
}
Alert.alert("Task deleted successfully!");
GetTasks();
}
}
]
)
}
return (
<View style={defaultStyles.container}>
<Stack.Screen
options={{
title: "Tasks",
headerTitleStyle: defaultStyles.title,
headerRight: () => {
return (
<View style={defaultStyles.buttonContainer}>
<Pressable style={defaultStyles.circularButton} onPress={GetTasks}>
<Ionicons name="refresh" size={22} color="#333" />
</Pressable>
<Button title="Logout" onPress={async () => await supabase.auth.signOut()} />
</View>
)
},
}}
/>
<View style={defaultStyles.buttonContainer}>
<Button title="Create Task" onPress={() => router.push("/createTask")} />
</View>
<SectionList
sections={taskSections}
keyExtractor={(item) => item.tId}
renderSectionHeader={({ section: { title } }) => <Text style={defaultStyles.subtitle}>{title}</Text>}
renderItem={({ item }) => {
const isOwner = session?.user.id === item.uId;
return (
<View style={defaultStyles.container}>
<Text style={defaultStyles.boldBody}>{item.title}</Text>
<Text style={defaultStyles.body}>{item.deadline}</Text>
{isOwner && (
<View style={defaultStyles.buttonContainer}>
<Button title="Edit" onPress={() => router.push({pathname: "/editTask", params: { tId: item.tId }})} />
<Button title="Delete" onPress={() => DeleteTask(item.tId)} />
</View>
)}
</View>
);
}}
renderSectionFooter={({ section }) =>
section.data.length === 0 ? (
<View style={defaultStyles.container}>
<Text style={defaultStyles.body}>{section.emptyMessage}</Text>
<View style={defaultStyles.separator} />
</View>
) : (
<View style={defaultStyles.separator} />
)
}
/>
</View>
)
}

69
app/createUser.tsx Normal file
View File

@@ -0,0 +1,69 @@
import { defaultStyles } from '@/constants/defaultStyles';
import { supabase } from '@/lib/supabase';
import { router, Stack } from 'expo-router';
import { useState } from 'react';
import { Alert, Button, Keyboard, KeyboardAvoidingView, Platform, Pressable, Text, TextInput, TouchableWithoutFeedback, View } from 'react-native';
export default function CreateUser() {
const [email, SetEmail] = useState('');
const [password, SetPassword] = useState('');
const SignUp = async () => {
if(email.trim() === '' || password.trim() === '') {
Alert.alert("All fields are required!");
return;
}
const {error} = await supabase.auth.signUp({
email: email,
password: password,
});
if (error) {
Alert.alert("User could not be created, please try again");
return;
}
router.replace("/");
}
return (
<View style={defaultStyles.container}>
<Stack.Screen
options={{
title: "Create User",
headerTitleStyle: defaultStyles.title,
}}
/>
<View style={defaultStyles.container}>
<Text style={defaultStyles.title}>Create User</Text>
<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === "ios" ? "padding" : "height"}>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={defaultStyles.container}>
<TextInput
style={defaultStyles.inputText}
placeholder="Enter Email"
value={email}
onChangeText={SetEmail}
autoCapitalize="none"
/>
<TextInput
style={defaultStyles.inputText}
placeholder="Enter Password"
value={password}
onChangeText={SetPassword}
secureTextEntry
/>
<Button title="Save" onPress={SignUp} />
<Button title="Cancel" onPress={() => router.back()} />
<Pressable onPress={() => router.push("/login")} style={defaultStyles.buttonContainer}>
<Text style={defaultStyles.linkText}>Already have an Account? login here</Text>
</Pressable>
</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
</View>
</View>
)
}

View File

@@ -1,9 +0,0 @@
import { Text, View } from "react-native";
export default function HomeScreen() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>Home</Text>
</View>
);
}

66
app/login.tsx Normal file
View File

@@ -0,0 +1,66 @@
import { defaultStyles } from "@/constants/defaultStyles";
import { supabase } from "@/lib/supabase";
import { router, Stack } from "expo-router";
import { useState } from "react";
import { Alert, Button, Keyboard, KeyboardAvoidingView, Platform, Text, TextInput, TouchableWithoutFeedback, View } from "react-native";
export default function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const login = async () => {
if(email.trim() === '' || password.trim() === '') {
Alert.alert("All fields are required!");
return;
}
const { error } = await supabase.auth.signInWithPassword({
email,
password
});
if (error) {
Alert.alert("Login failed, please check your credentials and try again");
return;
}
router.replace("/");
}
return (
<View style={defaultStyles.container}>
<Stack.Screen
options={{
title: "Login",
headerTitleStyle: defaultStyles.title
}}
/>
<View style={defaultStyles.container}>
<Text style={defaultStyles.title}>Login</Text>
<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === "ios" ? "padding" : "height"}>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={defaultStyles.container}>
<TextInput
style={defaultStyles.inputText}
placeholder="Enter Email"
value={email}
onChangeText={setEmail}
autoCapitalize="none"
/>
<TextInput
style={defaultStyles.inputText}
placeholder="Enter Password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<Button title="Login" onPress={login} />
<Button title="Cancel" onPress={() => router.push("/")} />
</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
</View>
</View>
)
}