I want to get the Key generated when I push data to Firebase database. I want to handle them with my own function,
So the issue is when the user fills the form he sends the data to our real-time DB, contained in this data are some images (optional), and I don't need to let the image object empty in DB, so how to handle this, and when the user needs to send an image I want to save this image in the same Order, not in New Order.
Node
Here is my function
handleOrder = () => {
const { nameOfProblem, description, userId, imageOfPrblem, providerId } = this.state;
const PushData = firebase.database().ref("request/" + providerId + "/" + userId + "/orders/");
const ref = firebase.storage().ref("users/" + userId + "/UserImageOrders/" + path);
let file = imageOfPrblem.uri;
const path = "img_" + imageOfPrblem.fileName;
var newOrderRef = PushData.push({
nameOfProblem: nameOfProblem,
description: description,
});
if (file) {
let keyG = newOrderRef.key; // Key Generated with .push()
PushData.child(keyG).update({ // didn't updated the key generated just add new element with new key !!
imageOfPrblem: imageOfPrblem
});
ref.put(file).then(() => {
console.log("File uploaded..")
});
}
}
handleImages = () => {
const options = {
title: "Select Images!",
storageOptions: {
skipBackup: true,
path: "images"
}
};
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.uri) {
this.setState({ imageOfPrblem: response });
}
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("ImagePicker Error: ", response.error);
} else if (response.customButton) {
console.log("User tapped custom button: ", response.customButton);
alert(response.customButton);
}
});
};
This seems to work fine for me:
var ref = firebase.database().ref("/55912103");
var newChildRef = ref.push({ firstChild: true });
console.log("new key: "+newChildRef.key);
ref.child(newChildRef.key).update({ secondChild: true });
After running this code, I end up with this JSON in the new child whose key gets logged:
"-LdgLWu_wBNNicFlPDGj" : {
"firstChild" : true,
"secondChild" : true
}
Live demo: https://jsbin.com/hovoleh/edit?js,console
Live JSON: https://stackoverflow.firebaseio.com/55912103.json?print=pretty
Update: if you just want to write both the existing data and new data to a new location:
var newOrderRef = PushData.push({
nameOfProblem: nameOfProblem,
description: description,
});
if (file) {
let keyG = newOrderRef.key; // Key Generated with .push()
PushData.child(keyG).update({
nameOfProblem: nameOfProblem,
description: description,
imageOfPrblem: imageOfPrblem
});
ref.put(file).then(() => {
console.log("File uploaded..")
});
}
The push ID from any Firebase snapshot ref is in ref.name().
I know it's been a while since the author created a post but maybe someone will find it useful.
The above answers are a bit wrong because, for example, after: newChildRef
var ref = firebase.database().ref("/55912103");
var newChildRef = ref.push({ firstChild: true });
newChildRef <--- promise
ref = rdb.ref('name_of_your_ref');
var childRef = ref.push({
IdUser: currentUserId,
ProductCategory: pCategory,
ProductDescription: pDesc,
ProductId: pId,
ProductName: pName,
ProductPrice: pPrice,
ProductQuantity: pQuan
}).catch(err => console.log(err.message));
childRef.then(item => {
ref.child(item.key).update({
IdKey: item.key
}).then(() => history.push('/delivery/basket'));
});
Greetings, Matthew
Related
This is from Colt Steele's YelpCamp.
This is my form.
I want to change the title, location, and description, because if one if my object variable has ', ", {, or }, JSON will fail to parse and the map doesn't load. So this is my code in the controllers campgrounds.js.
module.exports.updateCampground = async (req, res) => {
const geoData = await geocoder.forwardGeocode({
query: req.body.campground.location,
limit: 1
}).send();
const { id } = req.params;
const campground = await Campground.findByIdAndUpdate(id, { ...req.body.campground });
campground.title.replaceAll(/["]/g, "");
campground.title.replaceAll(/[']/g, "");
campground.title.replaceAll("{", "");
campground.title.replaceAll("}", "");
campground.location.replaceAll(/["]/g, "");
campground.location.replaceAll(/[']/g, "");
campground.location.replaceAll("{", "");
campground.location.replaceAll("}", "");
campground.description.replaceAll(/["]/g, "");
campground.description.replaceAll(/[']/g, "");
campground.description.replaceAll("{", "");
campground.description.replaceAll("}", "");
campground.geometry = geoData.body.features[0].geometry;
const imgs = req.files.map(f => ({ url: f.path, filename: f.filename }));
campground.images.push(...imgs);
await campground.save();
if (req.body.deleteImages) {
for (let filename of req.body.deleteImages) {
await cloudinary.uploader.destroy(filename);
}
await campground.updateOne({ $pull: { images: { filename: { $in: req.body.deleteImages } } } });
console.log(campground);
}
req.flash('success', 'Successfully updated a campground!');
res.redirect(`/campgrounds/${campground._id}`);
}
I use replaceAll() to change the variables of campground.title, campground.location, and campground.description, how come when I submit the form with the title of {'Hello'}, the campground.title value is still {'Hello'}. How come the value of title didn't update?
Let me know if I need to put other codes up and if I don't have enough information in the comment in case. Thank you.
I have a question, so i'm using AsyncStorage to store the user input data as a json format. However , while i'm checking whether the data are stored correctly using console.log, it always print out undefined, so i'm curious about how to access the data i store and print it out so that i can check if the data is correct? thanks!
Here's the json formate that i want the user input to store in
////JSON FORMAT////
const MyRecipeData = [
{
name: recipeName,
video_cover: selectedVideoCover,
video_url: UploadVideo,
servings: servingSize,
channel_name: channelName,
publish_date: uploadDate,
ingredients: ingredientsInput,
directions: directionsInput,
},
];
////JSON FORMAT////
and these are the function that called after the user pressing upload button, and i try to read it using getAllinput function, but not sure i did it right or not
////------- Save all DATA --------------------////
const SaveAllInput = async () => {
await AsyncStorage.setItem("MyRecipeData", JSON.stringify(MyRecipeData))
.then(() => {
alert("your Recipe " + MyRecipeData.name + " has been saved");
})
.catch(() => {
console.log("error");
});
getAllInput();
};
////------- Save all DATA --------------------////
////------- READING THE DATA THAT UPLOAD PREVIOUSLY-------- /////
const getAllInput = async () => {
try {
const NewRecipeData = await AsyncStorage.getItem("MyRecipeData");
NewRecipeData !== null ? JSON.parse(NewRecipeData) : null;
console.log(NewRecipeData);
return NewRecipeData;
} catch {
console.log(error);
}
};
////------- READING THE DATA THAT UPLOAD PREVIOUSLY-------- /////
the console.log(NewRecipeData) print out [{}] in my terminal, seems like i did not read my data properly
i tried to use getItem to read it out, but instead i got undefined or [{}]
const NewRecipeData = await AsyncStorage.getItem("MyRecipeData");
NewRecipeData !== null ? JSON.parse(NewRecipeData) : null;
You using const and you are redefining the variable, try to console.log like this :
const NewRecipeData = await AsyncStorage.getItem("MyRecipeData");
console.log(NewRecipeData);
You are caliing getAllInput(); without await
const SaveAllInput = async () => {
const MyRecipeData = [
{
name: recipeName,
video_cover: selectedVideoCover,
video_url: UploadVideo,
servings: servingSize,
channel_name: channelName,
publish_date: uploadDate,
ingredients: ingredientsInput,
directions: directionsInput,
},
];
await AsyncStorage.setItem('MyRecipeData', JSON.stringify(MyRecipeData))
.then(() => {
alert('your Recipe ' + MyRecipeData.name + ' has been saved');
})
.catch(() => {
console.log('error');
});
await getAllInput();
};
How do I make it so it does not just like the newest post and it will like the post that they clicked the like button on?
code:
postSearch.addEventListener("input", (ev) => {
async function findPosts() {
const postsRef = collection(firestore, "posts")
const q = query(postsRef, orderBy("createdAt"));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((post) => {
// doc.data() is never undefined for query doc snapshots
if (post.data().likes == undefined) {
post.data().likes = 0
}
function epicTest() {
let postData = {
description: post.data().description,
display_name: post.data().display_name,
createdAt: post.data().createdAt,
uid: post.data().uid,
title: post.data().title,
likes: post.data().likes + 1
}
console.log(post.id)
console.log(postData)
setDoc(doc(postsRef, post.id), postData)
console.log("this feature hasn't been added yet")
}
let items = querySnapshot.docs.map(post => {
if (post.data().title.includes(ev.target.value) || post.data().description.includes(ev.target.value)) {
return `<div id="postBox">
<h4 id="postName">${post.data().display_name}</h4>
<h1 id="postTitle">${post.data().title}</h1>
<h3 id="postDescription">${post.data().description}</h3>
<div id="likeContainer"><ion-icon name="thumbs-up-outline" id="likeBtn" onclick="epicTest()"></ion-icon><h3 id="likeCount">${post.data().likes}</h3></div>
</div>`
}
});
items.reverse()
postList.innerHTML = items.join('');
if (postList.innerText == "") {
postList.innerText = "no results found"
}
let likeBtn = document.querySelectorAll("#likeBtn")
likeBtn.forEach(item => {
item.addEventListener("click", (ev) => {
let postData = {
description: post.data().description,
display_name: post.data().display_name,
createdAt: post.data().createdAt,
uid: post.data().uid,
title: post.data().title,
likes: post.data().likes + 1
}
console.log(post.id)
console.log(postData)
setDoc(doc(postsRef, post.id), postData)
console.log("this feature hasn't been added yet")
})
})
});
}
findPosts()
})
The following example shows how you can use the function to run whenever a 'Like' button is clicked, check the below sample:
var postRef = new Firebase(firebaseURL + id);
postRef.child('like-count').once('value', function(snapshot) {
var currentLikes = snapshot.val() ? snapshot.val() : 0;
postRef.update({
'postID': id,
'like-count': currentLikes + 1
}, function(error) {
if (error) {
console.log('Data could not be saved:' + error);
} else {
console.log('Data saved successfully');
}
});
getLikeCount(id);
});
}
The basic idea behind this is to pass the post id as a parameter to the function that is called when clicking the like button.
Also check the following examples for similar implementations:
Like/Dislike function for Firebase
Creating like button using firestore and useeffect
Like-Dislike system using Firebase Database
How to implement like button concept
Like button functionality
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})
})
...
i am trying to get auto key with firebase functions.
event.data.key doesn't return the key. How can i listen isEnabled and when changed it true, add another data to notification ref with same key.
exports.sendNotificationWhenEnabled = functions.database.ref('/contents/{contentId}/isEnabled').onWrite(event => {
const isEnabled = event.data.val();
const contentId = event.data.key;
admin.database().ref('/contents/' + contentId).once('value', function(snapshot) {
console.log('Sending Notification to: ', contentId);
admin.database().ref('/notifications/' + contentId).push({
'asd': 'asd'
}).then(snapshot => {
console.log('finished');
});
});
return "FINISHED";
}
});
I found solution with event.params.contentId