Reputation: 313
i'm using Firebase with React and i have these collections:
so it goes like sheets/userId/sheetId/sheetData
how do i get the last two sheets (in this example the only two sheets) with all of their data from /sheetsData
in a nice format, so i can store it in a Redux store for example. Thanks
Upvotes: 0
Views: 763
Reputation: 1867
First you need to get the userID.... There are many ways of doing this. Here are two examples I personally use.
// ********* Add a listener from the database to monitor whos logged in. *********
firebase.auth().onAuthStateChanged((user) => {
// ********* If a user is logged in firebase will return the user object. THEY ARE NOT LOGGED IN THOUGH *********
if (user) {
console.log('onAuthStateChanged', user)
// ********* Then we call an official Firebase function through actions, this would probably be getSheets() for you *********
this.props.loginRequest(user);
} else {
console.log('No user signed in')
}
});
// ********* After logging in the found user from above we need to set them to redux store *********
let signedInUser = firebase.auth().currentUser;
if (signedInUser) {
this.props.loginRequest(signedInUser);
console.log('currentUserSignedIn', signedInUser)
} else {
console.log('no active user', signedInUser)
}
After acquiring the user id you can call a redux action to fetch a snapshot of this user with all their sheet's in an object of objects.
firebase.database().ref('users/' + user.uid).once('value').then(function (snapshot) {
// ******** This method is straight from their docs ********
// ******** It returns whatever is found at the path
xxxxx/users/user.uid ********
let username = snapshot.val();
console.log(' FOUND THIS USER FROM THE DB', username);
// now dispatch whatever redux store action you have to store the user
information
dispatch(userSet(username))
})
.catch((err) => console.log(err));
Lastly, I would suggest storing the sheets as an array of objects because currently it looks like you're using firebase's push method which creates unique ID's for each of the new sheets. This makes manipulation of them difficult because firebase will return to you an object of objects, that you CANT use .map, .filter, or .forEach on without knowing each unique ID.
Here is how I am using firebase with login https://github.com/GavinThomas1192/motoMechanicMeeKanic/blob/master/App/Actions/auth-actions.js
I like to package up the object locally and set it once to avoid deep nesting of firebase.
Upvotes: 1