Vue.js object properties are "hidden" after assignment - javascript

I can retrieve data from a Firebase database, but when I try to assign the fetched data from the database, the object properties require you to invoke a getter (I mean I can't access them after assignment)
This is the Vue instance.
Yes, I know. This is formatted weirdly, this is something that VS Code does for me...
export default {
name: "Home",
data() {
return {
users: []
};
},
created() {
db.collection("users")
.get()
.then(snapshot => {
snapshot.forEach(doc => {
let user = doc.data();
user.id = doc.id;
this.users.push(user);
console.log(this.users);
});
});
}
};
When I open up the console I need to click on three dots to get the actual data.

The following should do the trick:
export default {
name: "Home",
data() {
return {
users: []
};
},
created() {
db.collection("users")
.get()
.then(snapshot => {
let usersArray = [];
snapshot.forEach(doc => {
let user = doc.data();
user.id = doc.id;
usersArray.push(user);
});
this.users = usersArray;
console.log(this.users);
});
}
};

Related

Adonis maping inside map

I'm trying to use CASL library for user permissions, i load everything in one async function
const insuranceUser = await CompanyUser.findByOrFail('userId', currentUserRole.userId)
await insuranceUser.load('company')
await insuranceUser.company.load('products')
insuranceUser.company.products.forEach(async (p) => {
await p.load('packages')
p.packages.forEach(async (packg) => {
await packg.load('benefits')
await packg.load('additionalServices')
})
})
user = insuranceUser
and i get insuranceUser in another non async function 'user'
export const defineAbility = (user) => {
const { can, cannot, build } = new AbilityBuilder(Ability)
if (user.role === 'InsuranceAdmin') {
can('manage', 'Product', { companyId: user.company.id })
can('manage', 'Package', { productId: { $in: user.company.products.map((p) => p.id) } })
// Can't get package ids
can('manage', 'Benefit', {
packageId: {
$in: user.company.products.map((prod) => {
prod.packages.map((packg) => {
packg.id
})
}),
},
})
}
return build()
}
first i want to map products and then in this map i want to map product packages ids,
am getting "message": "Cannot read properties of undefined (reading 'map')"
How can i fix this can someone please help me.

How to store ID of record in Firebase cloud functions

I'm saving data in the collection in the following way:
const userEntry= {
UserId: "I want documentID here",
UserName: "",
creationDate: ""
}
const churchResult = await saveChurchData(userEntry)
const saveData = async (data: object) => {
return database.collection('users').add(data)
.then(snapshot => {
return snapshot.get().then(doc => {
doc.data()
return doc.id
}).catch(err => {
console.log('Error getting documents', err);
return null;
});
}).catch(err => {
console.log('Error getting documents', err);
return null;
});
}
Is there any way that I store "documentID" of users table in the place of UserId. How can we do that in firebase cloud functions? I'm unable to find a way to store the documentID in the documentation.
I tried following, but it is giving wrong ID not docuemntID:
const key =firebase.database().ref().push()
Since I don't see any saveChurchData() method in your code, I make the assumption that instead of doing
const churchResult = await saveChurchData(userEntry)
you wan to do
const churchResult = await saveData(userEntry)
The following would do the trick, by using the doc() method without specifying any documentPath:
const userEntry = {
UserName: "",
creationDate: ""
}
const churchResult = await saveData(userEntry)
const saveData = async (data: object) => {
try {
const docRef = database.collection('users').doc();
const docId = docRef.id;
await docRef.set({ UserId: docId, ...data });
return docId;
} catch (error) {
//...
}
}

Pass variable to created hook Vue.js for Firestore reference

My goal is to:
Load one document and get the value for "account"
Then load a new document with "account" as one of the document names in firestore. I am using this.account for the path
<script>
// eslint-disable-next-line
import firestore from "firestore";
// eslint-disable-next-line
import NewEmployee from "#/components/updatePopups/NewEmployee";
import db from "#/components/fbInit";
import firebase from "firebase";
export default {
// eslint-disable-next-line
components: { NewEmployee },
data() {
return {
account: "",
users: [],
acc:[],
};
},
computed: {
computed() {
const user = firebase.auth().currentUser;
const info = [];
db
.collection("userProfiles")
.doc(user.uid)
.get()
.then(doc => {
const doc1content = doc.data();
return doc1content.account;
console.log(doc1content.account)
});
}
},
created() {
const user = firebase.auth().currentUser;
let account = computed();
let empRef = db.collection('userProfiles').doc(this.account).collection('employees');
let empCollection = empRef.get()
.then(snapshot => {
this.users = [];
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
const data = {
id: doc.id,
Name: doc.data().Name,
GroupHex: doc.data().GroupHex,
DeviceType: doc.data().DeviceType,
UserIDInt: doc.data().UserIDInt,
SuperID: doc.data().SuperID,
misc: doc.data().misc,
Status: doc.data().Status,
};
this.users.push(data)
});
})
},
};
</script>
I keep getting undefined errors or value can't be "" or """
account is undefined
ReferenceError: computed is not defined
The reason I am not doing this all in one created hook is because I would like to use the snapshot feature to reload the page when there is a change automatically and I had trouble doing that when it was nested inside another doc.get(). I would like to have the "account" variable loaded and stored when the page is loaded(or before).
Any help would be greatly appreciated.

storing array state objects in asyncStorage

I want to store an array state using async storage. but everytime i reload the app, it comes up blank. below is a sample code, and I have shown only the functions for better clarity.
componentDidMount() {
this.getDataSync();
}
getDataSync = async () => {
try {
const list = await AsyncStorage.getItem(LIST_STORAGE_KEY);
const parsedList = JSON.parse(list);
const obj = Object.keys(parsedList);
this.setState({ isDataReady: true, list: obj || [] });
} catch (e) {
Alert.alert('Failed to load list.');
}
}
handleAdd() {
const { firstname, lastname, email, phone} = this.state;
const ID = uuid();
const newItemObject = {
key: ID,
firstname: firstname,
lastname: lastname,
email: email,
phone: phone,
image: null,
};
this.setState(prevState => ({
list: [...prevState.list, newItemObject]
}));
this.saveItems(this.state.list);
}
saveItems = list => {
AsyncStorage.setItem(LIST_STORAGE_KEY, JSON.stringify(list));
};
You are not saving your list but getting keys from the list. const obj = Object.keys(parsedList); you are saving array indexes to state.
getDataSync = async () => {
try {
const list = await AsyncStorage.getItem(LIST_STORAGE_KEY);
const parsedList = JSON.parse(list);
this.setState({
isDataReady: true,
list: Array.isArray(parsedList) && parsedList.length && parsedList || []
});
} catch (e) {
Alert.alert('Failed to load list.');
}
}
Also pass saveItems as a callback to save the correct data.
this.setState(prevState => ({
list: [...prevState.list, newItemObject]
}), () => this.saveItems(this.state.list));
The .setState() method is may be asynchronous, so the result of setting the state, cannot be used immediately after setting it. If you want to use the results of setting the state, you should use the callback (2nd param), which is called after the state is actually set:
this.setState(
prevState => ({
list: [...prevState.list, newItemObject]
}),
() => this.saveItems(this.state.list)
);

access firebase data id within push

complete noob here.
Trying to retrieve the firebase unique id from the first data push to use in the second so that I can reference the data between the two data sets. I used stackoverflow answers to retrieve the key, but my code didnt work.
(If you have a better way of referencing the two items other than utilizing firebase unique id, Im all for it!) thanks!!
export const GROUP_CREATE = 'group_create';
export const groupCreate = ({ name, course, members }) => {
const { currentUser } = firebase.auth();
return (dispatch) => {
var pushedRef = firebase.database().ref(`/groups`).push({ name })
var dataId = pushedRef.key
.then(
firebase.database().ref('/groups')
.push({ name, dataId, course, members }))
.then(() => {
dispatch({ type: GROUP_CREATE });
Actions.groupMain({ type: 'reset' });
});
};
};
I figured it out!
export const GROUP_CREATE = 'group_create';
export const groupCreate = ({ name, course, members }) => {
const { currentUser } = firebase.auth();
var myRef = firebase.database().ref('/groups').push();
var groupId = myRef.key;
return (dispatch) => {
myRef.push({ name, course, members })
.then(
firebase.database().ref(`/users/${currentUser.uid}/groups`)
.push({ name, groupId }))
.then(() => {
dispatch({ type: GROUP_CREATE });
Actions.groupMain({ type: 'reset' });
});
};
};

Categories

Resources