access firebase data id within push - javascript

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' });
});
};
};

Related

I am using provide/inject to pass the data within components , I've this function using compute, I am trying to run and pass it's result in provide

I have 4 functions, for 1st three functions, I can send the data in provide. For 4th function(
getViewApplicationDetails
), I am trying to fetch api and get application name, now I want that in mounted because, I want the application name as soon as component is rendered so I am trying to execute it in mounted but when I call the it, it's giving me error. Initially application name is empty and it should have the current application name when I fetch the api, the same application name will be used in provide and then I can use that in inject and then in any other component.
import { computed, inject, onMounted, provide, reactive } from "vue";
export const initStore = () => {
onMounted(()=>{
this.getViewApplicationDetails()
});
// State
const state = reactive({
name: "Bob Day",
email: "bob#martianmovers.com",
applicationName: "",
breadcrumbsData: [
{
name: "Home",
text: 'Home',
disabled: false,
href: '/'
}
]
});
// Getters
const getUsername = computed(() => state.name);
const getEmail = computed(() => console.log("state.email",state.email));
const getBreadcrumbsData=computed(()=>state.breadcrumbsData)
console.log("state.applicationName",state.applicationName)
//this is the temporary function
const getApplicationName=computed(()=>state.applicationName)
const getViewApplicationDetails=computed(()=> {
var viewApplicationDetailsParams = {
applicationId: this.$route.query.applicationId,
applicationStatus:this.$route.query.appStatus,
authType: "api",
clientId: process.env.VUE_APP_EXTERNAL_API_CLIENT_ID,
clientSecret: process.env.VUE_APP_EXTERNAL_API_CLIENT_SECRET
};
axios({
method: "post",
url: process.env.VUE_APP_BLUJ_BACKEND_URL + "/viewapplicationDefinition",
data: viewApplicationDetailsParams,
headers: {
"content-type": "application/json",
},
})
.then((response) =>{
this.viewDefinitionResponse = response.data.Definitions;
let applicationName = viewDefinitionResponse.application_display_name.en;
console.log("tyfgyhkjlfhgjklnm",applicationName)
setApplicationName(applicationName)
})
.catch((error) => {
console.log("error", error);
});
});
getViewApplicationDetails()
// Mutations
const setUsername = (name) => {
state.name = name;
};
const setEmail = (email) => {
state.email = email;
};
const setBreadCrumbsData=(breadcrumbsData)=>{
state.breadcrumbsData=breadcrumbsData;
}
const setApplicationName=(appName)=>{
state.applicationName=appName
}
// Actions
const updateUsername = (name) => {
setUsername(name);
};
const updateEmail = (email) => {
setEmail(email);
};
provide("getUsername", getUsername);
provide("getEmail", getEmail);
provide("updateUsername", updateUsername);
provide("updateEmail", updateEmail);
provide("getViewApplicationDetails", getViewApplicationDetails);
provide("getApplicationName", getApplicationName);
provide("getBreadcrumbsData", getBreadcrumbsData);
};
export const useStore = () => ({
getUsername: inject("getUsername"),
getEmail: inject("getEmail"),
updateUsername: inject("updateUsername"),
updateEmail: inject("updateEmail"),
viewApplicationDetails: inject("getViewApplicationDetails"),
getBreadcrumbsData: inject("getBreadcrumbsData"),
getApplicationName: inject("getApplicationName")
});
This is the code snippet.
const getUsername = computed(() => state.name);
const getEmail = computed(() => console.log("state.email",state.email));
const getBreadcrumbsData=computed(()=>state.breadcrumbsData)
I am getting data for this, but for getViewApplicationDetails, it's not working. While hovering over rest of the functions, it is showing "const getUsername: ComputedRef", like this. But, for getViewApplicationDetails, it shows "const getViewApplicationDetails: ComputedRef", this. I think it is not taking it as function or something. Error image is in the link.enter image description here

Firebase: Vue.js : Not able to connect storage with database

I am working on my first Vue-Projeect with firebase.
I would like to create locations with particular images and other data.
I am working with a tutorial which is unfortunately a bit outdated. Currently I am struggeling with the connection of firebase storage with firebase database.
I am not able to push the downloadable imageUrl in the firebase storage and store it in the database.
Can you guys help me out here?
Thank you
createLocation( {commit, getters}, payload) {
const location = {
title: payload.title,
location: payload.location,
description: payload.description,
creationDate: payload.creationDate,
rating: payload.rating,
coordinates: payload.coordinates,
filters: payload.filters,
creatorId: getters.user.id
}
let imageUrl
let key
firebase.database().ref('locations').push(location)
.then((data) => {
key = data.key
return key
})
.then(key => {
const filename = payload.image.name
const ext = filename.slice(filename.lastIndexOf('.'))
console.log(payload.image)
return firebase.storage().ref('locations/' + key + ext).put(payload.image)
})
.then(fileData => {
imageUrl = fileData.metadata.getDownloadURL
return firebase.database().ref('meetups').child(key).update({imageUrl: imageUrl})
})
.then(() => {
commit('createLocation', {
...location,
imageUrl:imageUrl,
id: key
})
})
.catch((error) => {
console.log(error)
})
},
If you look at the reference documentation for metadata.downloadURL it says:
deprecated
Use Reference.getDownloadURL instead. This property will be removed in a future release.
Determining the download URL for a file now requires another roundtrip to the server, so you'll need another then block for that:
firebase.database().ref('locations').push(location)
...
.then(key => {
const filename = payload.image.name
const ext = filename.slice(filename.lastIndexOf('.'))
console.log(payload.image)
return firebase.storage().ref('locations/' + key + ext).put(payload.image)
})
.then(fileData => {
return fileData.ref.getDownloadURL();
})
.then(imageUrl => {
return firebase.database().ref('meetups').child(key).update({imageUrl: imageUrl})
})
...

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)
);

Vue.js object properties are "hidden" after assignment

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);
});
}
};

Why isn't my pushKey being added to my User's post object?

When a user makes a post, I want to take the pushKey of the post and then add it in to the User object in order to store in a list of posts they have made.
I had assumed that my logic was correct but it seems not. Everything is console logging so far.
Here is the Create Post action:
export const createPostNoImage = (text, firstName, university, avatar) => {
const timeDate = new Date().getTime();
const { currentUser } = firebase.auth();
const { uid } = currentUser;
const anonAvatarKey = Math.floor(Math.random() * 10);
return (dispatch) => {
const pushKey = firebase.database().ref('/social/posts/').push().key;
const postObject = {
text,
comment_count: 0,
vote_count: 0,
author: {
uid,
anon_avatar_key: anonAvatarKey,
first_name: firstName,
photo_avatar: avatar,
university
},
created_at: timeDate,
};
firebase.database().ref(`/social/posts/${pushKey}`)
.update(postObject)
.then(() => {
postObject.uid = pushKey;
addPostIdToProfile(pushKey);
dispatch({ type: CREATE_POST, payload: postObject });
});
};
};
The above works just fine, I then call the addPostIdToProfile() function:
const addPostIdToProfile = (pushKey) => {
const { currentUser } = firebase.auth();
console.log(pushKey);
firebase.database().ref(`/social/users/${currentUser.uid}`)
.update((user) => {
if (!user.posts) {
user.posts = {};
}
user.posts[pushKey] = true;
return user;
});
};
It is this that is not updating in the database. Can someone please tell me why?

Categories

Resources