componentDidMount() { this.unsubscribe = firebase.auth().onAuthStateChanged((user) => { if (user) { // User is signed in. } }); } componentWillUnmount() { if (this.unsubscribe) { this.unsubscribe(); } }
// On mount, subscribe to ref updates componentDidMount() { this.ref = firebase.database().ref('posts/1234'); this.ref.on('value', this.handlePostUpdate); } // On unmount, ensure we no longer listen for updates componentWillUnmount() { if (this.ref) { this.ref.off('value', this.handlePostUpdate); } } // Bind the method only once to keep the same reference handlePostUpdate = (snapshot) => { console.log('Post Content', snapshot.val()); }
コレクションの取得 firebase.firestore() .collection('posts') .get() .then(querySnapshot => { // Access all the documents in the collection const docs = querySnapshot.docs; // Access the list of document changes for the collection const changes = querySnapshot.docChanges; // Loop through the documents querySnapshot.forEach((doc) => { const value = doc.data(); }) })
ドキュメントの追加 firebase.firestore() .collection('posts') .add({ title: 'Amazing post', }) .then(() => { // Document added to collection and ID generated // Will have path: `posts/{generatedId}` })
ドキュメントの更新 var washingtonRef = firebase.firestore().collection("cities").doc("DC"); // Set the "capital" field of the city 'DC' return washingtonRef.update({ capital: true }) .then(function() { console.log("Document successfully updated!"); }) .catch(function(error) { // The document probably doesn't exist. console.error("Error updating document: ", error); });
特定のフィールドの削除 var cityRef = firebase.firestore().collection('cities').doc('BJ'); // Remove the 'capital' field from the document var removeCapital = cityRef.update({ capital: firebase.firestore.FieldValue.delete() });