npm i firebase
make file firebaseConnection.ts
import {initializeApp} from 'firebase/app';
import {getDatabase} from 'firebase/database';
const firebaseConfig = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
measurementId: '',
};
const app = initializeApp(firebaseConfig);
export const db = getDatabase(app);
import {ref, set} from 'firebase/database';
import {db} from '../../firebaseConnection';
CRUD operations:
const handleChange = (key: string) => (value: string) => {
setForm({
...form,
[key]: value,
});
};
const onReadPress = () => {
const mainRef = ref(db, 'users/');
onValue(mainRef, snapshot => {
const data = snapshot.val();
console.log('data:', data);
Alert.alert('data:', JSON.stringify(data));
});
};
const onInsertPress = () => {
set(ref(db, `users/${form.phone}`), {
fName: form.name,
age: form.age,
})
.then(() => {
Alert.alert('data Inserted to server successfully');
})
.catch(error => {
Alert.alert('Something went Wrong!..', error);
});
};
const onUpdatePress = () => {
const mainRef = ref(db, 'users/');
onValue(mainRef, snapshot => {
const data = snapshot.val();
console.log('data:', data);
});
update(ref(db, `users/${form.phone}`), {
fName: form.name,
age: form.age,
})
.then(() => {
Alert.alert('data updated successfully in the firebase.');
})
.catch(error => {
Alert.alert('something went wrong!...', error);
});
};
const onDeletePress = () => {
remove(ref(db, `users/${form.phone}`))
.then(() => {
Alert.alert('Data removed successfully');
})
.catch(error => {
Alert.alert('Something went wrong!...', error);
});
};