First, we need to set up Firebase for our project. If you haven’t already:
- Go to the Firebase Console.
- Create a new project.
- Enable Firestore and Authentication (Email/Password method).
- Add your app (iOS/Android) and follow the instructions to set it up.
Install Firebase SDK
In your project directory, install the Firebase SDK:
bashCopy codenpm install firebase
Step 2: Set Up Firebase Configuration
Create a new file called firebaseConfig.js
in your project directory and add your Firebase configuration:
javascriptCopy code// firebaseConfig.js
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { getAuth } from 'firebase/auth';
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);
export { db, auth };
Make sure to replace the placeholder values with your actual Firebase project details.
Step 3: User Authentication
Add Authentication Functions
Update App.js
to include authentication functions:
javascriptCopy codeimport React, { useEffect, useState } from 'react';
import { StyleSheet, View, FlatList, Alert } from 'react-native';
import { Provider as PaperProvider, TextInput, Button, List, Appbar } from 'react-native-paper';
import { db, auth } from './firebaseConfig'; // Import Firebase
import { signInWithEmailAndPassword, createUserWithEmailAndPassword } from 'firebase/auth';
import { collection, addDoc, getDocs } from 'firebase/firestore';
const App = () => {
const [items, setItems] = useState([]);
const [textInput, setTextInput] = useState('');
const [editIndex, setEditIndex] = useState(null);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(currentUser => {
setUser(currentUser);
if (currentUser) {
loadItems(currentUser.uid);
}
});
return () => unsubscribe();
}, []);
const loadItems = async (userId) => {
const querySnapshot = await getDocs(collection(db, userId));
const loadedItems = querySnapshot.docs.map(doc => ({ key: doc.id, ...doc.data() }));
setItems(loadedItems);
};
const addItem = async () => {
if (textInput.trim() && user) {
const newItem = { text: textInput, completed: false };
const docRef = await addDoc(collection(db, user.uid), newItem);
setItems([...items, { key: docRef.id, ...newItem }]);
setTextInput('');
}
};
const register = async () => {
try {
await createUserWithEmailAndPassword(auth, email, password);
setEmail('');
setPassword('');
} catch (error) {
console.error(error);
}
};
const login = async () => {
try {
await signInWithEmailAndPassword(auth, email, password);
setEmail('');
setPassword('');
} catch (error) {
console.error(error);
}
};
return (
<PaperProvider>
<Appbar.Header>
<Appbar.Content title="My Item List" />
</Appbar.Header>
<View style={styles.container}>
{user ? (
<>
<TextInput
label="Add or edit an item"
value={textInput}
onChangeText={setTextInput}
style={styles.input}
/>
<Button mode="contained" onPress={addItem}>Add Item</Button>
<FlatList
data={items}
renderItem={({ item }) => (
<List.Item
title={item.text}
onPress={() => toggleCompletion(item)}
right={props => (
<Button onPress={() => startEditing(item)}>Edit</Button>
)}
onLongPress={() => confirmDelete(item)}
/>
)}
keyExtractor={(item) => item.key}
/>
</>
) : (
<>
<TextInput label="Email" value={email} onChangeText={setEmail} />
<TextInput label="Password" value={password} secureTextEntry onChangeText={setPassword} />
<Button mode="contained" onPress={register}>Register</Button>
<Button mode="outlined" onPress={login}>Login</Button>
</>
)}
</View>
</PaperProvider>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#fff',
},
input: {
marginBottom: 10,
},
});
export default App;
Leave a Reply