如何在react-redux-firebase中获取Firestore实例并解决set方法异常
2. Correctly Using Firestore's set Method
The firebase.set() method you were using is for Realtime Database, not Firestore. To write to Firestore, you need to use the official Firestore instance methods. Here's the updated action:
Modified authAction.js:
export const registerUser = user => async (dispatch, getState, { getFirebase, getFirestore }) => { const firebase = getFirebase(); const firestore = getFirestore(); // Now this will initialize correctly try { let createdUser = await firebase.auth().createUserWithEmailAndPassword(user.email, user.password); console.log('createdUser', createdUser); await createdUser.user.updateProfile({ displayName: user.displayName }); let newUser = { displayName: user.displayName, createdAt: firestore.FieldValue.serverTimestamp() // Use Firestore's server timestamp } console.log('new user', newUser); // Firestore's official way to set a document await firestore.collection('users').doc(createdUser.user.uid).set(newUser); dispatch(closeModal()) } catch (err) { console.log(err.message) } }
Key changes here:
- We destructure both
getFirebaseandgetFirestorefrom the thunk extra argument - Use
firestore.collection('users').doc(uid).set()instead offirebase.set() - Reference
firestore.FieldValue.serverTimestamp()instead offirebase.firestore.FieldValue(more consistent)
3. Fixing the Permission Denied Error
By default, Firestore's security rules block all read/write operations. You need to update these rules to allow authenticated users to write their own user document.
Go to your Firebase Console → Firestore Database → Rules tab, and replace the default rules with:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // Allow authenticated users to read/write their own user profile match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; } } }
Note: For development, you could temporarily use
allow read, write: if request.auth != null;to allow all authenticated users access, but make sure to tighten this for production!
内容的提问来源于stack exchange,提问作者Deepankar Singh

