Skip to content
Snippets Groups Projects
Commit d823e499 authored by Dominik Fuhrmann's avatar Dominik Fuhrmann
Browse files

initialize

parent 9508e173
No related branches found
No related tags found
No related merge requests found
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
// import components
import List from './app/screens/List';
export default function App() {
return (
<View style={styles.container}>
<Text>Open up App.tsx to start working on your app!</Text>
<StatusBar style="auto" />
</View>
);
}
const Stack = createNativeStackNavigator();
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="My Todos" component={List} />
</Stack.Navigator>
</NavigationContainer>
);
}
\ No newline at end of file
// import firebase and firebase database
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
// initalize connection with firebase
const firebaseConfig = {
apiKey: "AIzaSyBvl6QblBMRXTeh5ldYNLXr4FSorNGW2b0",
authDomain: "moco-todo-list.firebaseapp.com",
projectId: "moco-todo-list",
storageBucket: "moco-todo-list.firebasestorage.app",
messagingSenderId: "528059908087",
appId: "1:528059908087:web:dd49c795069310d65bb8f2"
};
export const FIREBASE_APP = initializeApp(firebaseConfig);
export const FIRESTORE_DB = getFirestore(FIREBASE_APP);
export const FIREBASE_AUTH = getAuth(FIREBASE_APP);
\ No newline at end of file
// import react modules
import { View, StyleSheet, Text, TextInput, Button, SafeAreaView, TouchableOpacity, FlatList } from 'react-native';
import React, { useEffect, useState } from 'react';
import { addDoc, collection, deleteDoc, doc, onSnapshot, updateDoc } from 'firebase/firestore';
import { Ionicons, Entypo } from '@expo/vector-icons';
// import own firebase config
import { FIRESTORE_DB } from '../../FirebaseConfig';
// define the ToDo element structure
export interface Todo {
done: boolean;
id: string;
title: string;
}
// list component
const List = () => {
// manages all todo elements
const [todos, setTodos] = useState<any[]>([]);
// useState receives value after user input in text input
const [todo, setTodo] = useState('');
const addTodo = async () => {
try {
const docRef = await addDoc(collection(FIRESTORE_DB, 'todos'), {
title: todo,
done: false
});
setTodo('');
console.log('Document written with ID: ', docRef.id);
} catch (e) {
console.error('Error adding document: ', e);
}
};
// executed while rendering list component, executed one time (due to [])
useEffect(() => {
// create reference to db
const todoRef = collection(FIRESTORE_DB, 'todos');
// check for changes in db collection, firebase informs device with snapshot event
const subscriber = onSnapshot(todoRef, {
// snapshots includes current todo collection with all entries
// next is executed every time something in the db is changed
next: (snapshot) => {
// create new array
const todos: any[] = [];
// fill array with all saved todos
snapshot.docs.forEach((doc) => {
todos.push({
id: doc.id,
...doc.data()
});
});
// update useState
setTodos(todos);
}
});
// // Unsubscribe from events when no longer in use
return () => subscriber();
}, []);
// render and show todo elements in the list
const renderTodo = ({ item }: any) => {
const ref = doc(FIRESTORE_DB, `todos/${item.id}`);
const toggleDone = async () => {
updateDoc(ref, { done: !item.done });
};
const deleteItem = async () => {
deleteDoc(ref);
};
return (
<View style={styles.todoContainer}>
<TouchableOpacity onPress={toggleDone} style={styles.todo}>
{/* show icon depending on state (done or not) */}
{item.done && <Ionicons name="checkmark-circle" size={32} color="green" />}
{!item.done && <Entypo name="circle" size={32} color="black" />}
<Text style={styles.todoText}>{item.title}</Text>
</TouchableOpacity>
<Ionicons name="trash-bin-outline" size={24} color="red" onPress={deleteItem} />
</View>
);
};
return (
<View style={styles.container}>
{/* input formular */}
<View style={styles.form}>
<TextInput
style={styles.input}
placeholder="Add new todo"
onChangeText={(text) => setTodo(text)}
value={todo}
/>
<Button onPress={addTodo} title="Add Todo" disabled={todo === ''} />
</View>
{/* check if todos array has elements to show; loaded by snapshot subscriber */}
{todos.length > 0 && (
<View>
{/* load Flatlist with todos array */}
<FlatList
data={todos}
// render todo elements according to renderTodo function
renderItem={renderTodo}
// set todo id as list key
keyExtractor={(todo) => todo.id}
// disabled function which removes not visible elements from memory
// removeClippedSubviews={true}
/>
</View>
)}
</View>
);
};
// css styling
const styles = StyleSheet.create({
container: {
marginHorizontal: 20
},
form: {
marginVertical: 20,
flexDirection: 'row',
alignItems: 'center'
},
input: {
flex: 1,
height: 40,
borderWidth: 1,
borderRadius: 4,
padding: 10,
backgroundColor: '#fff'
},
todo: {
flexDirection: 'row',
flex: 1,
alignItems: 'center'
},
todoText: {
flex: 1,
paddingHorizontal: 4
},
todoContainer: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#fff',
padding: 10,
marginVertical: 4
}
});
// component export
export default List;
\ No newline at end of file
// ensures that firebase loads correctly
const { getDefaultConfig } = require('@expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push('cjs');
module.exports = defaultConfig;
\ No newline at end of file
This diff is collapsed.
Based on https://galaxies.dev/react-native-firebase (last access: 28.11.2024)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment