Not able to delete document from firestore database v9 - reactjs

There is a collection users and inside user there is a document userID and inside this document there is another collection favourite and inside this collection , there is id's of saved favourite data favouriteId.
So i want to delete that data inside favourite colletion.
My db look likes:-
users(collection)>userID(document)>favourite(collection)>favouriteId(document)
Here is my code for that:
const deleteDoc = async (id) => {
const userRef = collection(db, "users");
const favRef = collection(
userRef,
`${firebaseAuth?.currentUser?.uid}/favourite`
);
const favId = doc(favRef, id);
await deleteDoc(favId);
};
favouriteId=id ,
userId=firebaseAuth?.currentUser?.uid
I use firebase v9.

your code is Most of correct you just need some changings in code like that
const deleteDocu = async (userId, favouriteId) => {
const userRef = collection(db, "users");
const favRef = collection(userRef, userId, "favourite");
const favId = doc(favRef, favouriteId);
await deleteDoc(favId);
};

You are naming your function in the same way as the Firebase function.
Just change the function name
const deleteDocu = async (id) => {
const userRef = collection(db, "users");
const favRef = collection(
userRef,
`${firebaseAuth?.currentUser?.uid}/favourite`
);
const favId = doc(favRef, id);
await deleteDoc(favId);
};

Related

I can't filter firestore for React native

I can't get any output in console, I want to sync 'title' to 'asdasd' which I want to do.
async function getPost (){
const li = [];
const storeDb=firebase.firestore()
const postDetailsRef = collection(storeDb,'Post');
const postQuery = query(postDetailsRef,where('title', '==','asdasdt'));
const querySnapshot = await getDocs(postQuery);
querySnapshot.forEach((doc)=>{
console.log('hop doc',doc.data())
})
}
I tried this with my firestore and it's working properly
const db = getFirestore(firebaseApp);
const test = query(collection(db, 'development', data.id, 'messages'), where('index','==', 1));
const testSnapshot = await getDocs(test);
testSnapshot.docs.map(doc =>
{
console.log( doc.data())
});
because you are using getDocs and query, i assume you use modular firebase v9. Try changing
const storeDb=firebase.firestore()
to
const storeDb = getFirestore(yourfirebaseApp);
according to this firebase document

hardhat tasks don't persist data on local network

I create a little NFT marketplace using solidity and hardhat. I have a JSON file with the NFT details and I wrote a hardhat task for automating the process.
task("populate-market", "populate market with nfts").setAction(async function (
taskArguments,
hre
) {
const [owner] = await hre.ethers.getSigners();
const Market = await hre.ethers.getContractFactory("NFTMarket");
const market = await Market.deploy(owner.address);
await market.deployed();
const marketAddress = market.address;
/* deploy the NFT contract */
const Item = await hre.ethers.getContractFactory("Item");
const nft = await Item.deploy(marketAddress);
await nft.deployed();
for (const item of nfts) {
const transaction = await nft.createToken(item.url);
const tx = await transaction.wait();
const event = tx.events[0];
const tokenId = event.args[2].toNumber();
const price = hre.ethers.utils.parseUnits(item.price.toString(), "ether");
await market.createMarketItem(nft.address, tokenId, price, item.supply);
}
console.log(await market.fetchMarketItems());
console.log("done!");
});
the problem it's when I load the data in my react app; I created an function getNfts() like this:
useEffect(() => getNfts(), []);
const getNfts = async () => {
const provider = new ethers.providers.JsonRpcProvider();
const nftContract = new ethers.Contract(NFT_ADDRESS, NFT.abi, provider);
const marketContract = new ethers.Contract(
MARKET_ADDRESS,
Market.abi,
provider
);
const data = await marketContract.fetchMarketItems();
console.log(data);
};
in this function data it returns empty array but, in task the console.log(await market.fetchMarketItems()); it returns all nfts. I don't understand why in the task it returns data but, in react it shows me an empty array. How to fix this?
Try to do this:
async function getNfts() {
// The rest of the code goes here
}
Basically use a function instead a variable asigned to a function. Sometimes there are errors with the this keyword that are not being passed correctly and it breaks the functionality of the library.

Deletion in FireStore (Latest Snip)

I have a Data Table i want to delete every document inside collection before invoke loadCheckOut.
How can i dow that with latest JS Syntax.
I am using React JS, and it initilize DB from getDb() method so methods like db.collection() not work on it i want a complete moduler solution
const loadCheckout = async (priceId) => {
//before adding we must delete existing collection
const docRef_x = collection(db, `customers/${user.uid}/checkout_sessions`);
const snapshot = await getDocs(docRef_x);
const x = await deleteDoc(snapshot);
const docRef = await addDoc(
collection(db, `customers/${user.uid}/checkout_sessions`),
{
price: priceId,
success_url: window.location.origin,
cancel_url: window.location.origin,
}
);
const ref = collection(db, `customers/${user.uid}/checkout_sessions`);
const snap = onSnapshot(
ref,
{ includeMetadataChanges: true },
async (doc) => {
var error = null,
sessionId = null;
var first = true;
doc.forEach((ele) => {
if (first) {
error = ele.data().error;
sessionId = ele.data().sessionId;
first = false;
}
});
console.log(sessionId);
if (error) {
alert(error);
}
if (sessionId) {
const stripe = await loadStripe(stripe_public_key);
stripe.redirectToCheckout({ sessionId });
}
}
);
};
This won't work:
const snapshot = await getDocs(docRef_x);
const x = await deleteDoc(snapshot);
The deleteDoc function requires a single DocumentReference, while your snapshot is a QuerySnapshot. This has very little to do with the change in syntax, as snapshot.delete() also wouldn't have worked in v8 of the SDK and earlier.
To delete the documents in the query snapshot, loop over the results and delete them one by one:
snapshot.forEach((doc) => {
deleteDoc(doc.ref);
});

Firebase firestore WEB v.9 retrieve data ID-s from collection where that current user ID contains

I am trying to retrieve specific data from firebase, in my redux store I have uniq id that I can get in any page like this
const currentUser = useSelector(selectLoggedInUser);
console.log(currentUser.id) // "71dc954d-d2a4-4892-8257-98696fe776cd" this is peace of doc name in "dms" collection
I want all doc-s that contains this ID "71dc954d-d2a4-4892-8257-98696fe776cd", how can I query it???
This is how I'm setting "dms" messages
export const sentDirectMsg = async ({ toUid, currentUid, message, name }) => {
const collecitonRef = await dmCollection(toUid, currentUid);
await addDoc(collecitonRef, {
timestamp: serverTimestamp(),
message,
name,
});
};
const dmCollection = async (toUid, currentUid) => {
const idPair = [currentUid, toUid].sort().join("_");
return collection(db, "dms", idPair, "messages");
};
I'm not enough clear sorry for that(just don't have enough experience), I'll try my best.
I'm trying to create Slack like app(I have many pages and function that I exporting from one place to another), I will show how I implement the channels messages sent & get from firebase, then explain how I make direct messages
//Function that sent message to exact channelId /channels/someChannelId/messages
// channelId is literal with dynamic id
export const sentMsg = async ({ name, message, channelId }) => {
await addDoc(collection(db, "channels", channelId, "messages"), {
timestamp: serverTimestamp(),
message,
name,
});
};
//Getting data from channel
const messagesRef = query(
collection(db, `channels/${channelId}/messages`),
orderBy("timestamp")
);
onSnapshot(messagesRef, (snapshot) => {
setMessages(snapshot.docs);
});
Now as I need DM I can't make it same way because it need some privacy, only 2 person should see the messages, so I need 2 uniq person that has uniq id and their collection of messages also is uniq(so that only they can see each other messages),in general when I register the users in my app I also save with them uniq ID for example this "71dc954d-d2a4-4892-8257-98696fe776cd",
//This is how I sent direct messages
// toUid - to whom I should sent
// currentUid - is who is sent
const sentDirectMsg = async ({
toUid,
currentUid,
message,
name,
}) => {
const collecitonRef = await dmCollection(toUid, currentUid);
await addDoc(collecitonRef, {
timestamp: serverTimestamp(),
message,
name,
});
};
const dmCollection = async (toUid, currentUid) => {
const idPair = [currentUid, toUid].sort().join("_");
return collection(db, "dms", idPair, "messages");
};
// As I'm sorting this two uniq ID-s from where person sent-s the message it is always same collection reference. My question is can I somehow by "query" or by "where" get all docs that contains current user ID???
Edited:
If I understood correctly, you want to get a document which id contains a part of the id you are looking for.
Using array-contains should do the trick:
const dmsRef = collection(db,"dms");
const docRef = query(dmsRef, where("idPair", "array-contains", id)); //for example id = "71dc954d-d2a4-4892-8257-98696fe776cd"
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
I based my example on this link from the official documentation.
If your data model is centered toward users being identified through their unique IDs, then you can store your data first hand to reflect his model:
const userData = {
name: 'Marouane',
state: 'BN',
country: 'TUN'
};
// Add the user document in collection `dms`, with the id being the user ID
const res = await db.collection('dms').doc('71dc954d-d2a4-4892-8257-98696fe776cd').set(userData);
You can then query the user document using its unique identifier:
Firebase v8
const userRef = db.collection('dms').doc('71dc954d-d2a4-4892-8257-98696fe776cd');
const doc = await userRef();
if (!doc.exists) {
console.log('No such user!');
} else {
console.log('User dms data:', doc.data());
}
EDIT (Added firebase v9 - modular):
import { getFirestore, ref, onValue } from "firebase/firestore";
const db = getFirestore(firebaseApp);
const userRef = ref(db, 'dms/71dc954d-d2a4-4892-8257-98696fe776cd');
onValue(userRef, (snapshot) => {
const data = snapshot.val();
console.log(data);
});
In case your document id is not known in advance, you can query for all available documents and filter out ones that does not match your user id:
import { getFirestore, collection, query, where, getDocs } from "firebase/firestore";
const db = getFirestore(firebaseApp);
const q = query(collection(db, "dms"));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
if (doc.id.startsWith('71dc954d-d2a4-4892-8257-98696fe776cd')) {
console.log(doc.data());
}
});
Meanwhile, this approach will cause great performance degradation and would be better traded with a storage re-design.

String useState Value Is Empty after Storing a Value in an API Response to It

What I am trying to do here is to extract the id (Number) from an API response, parse it into String, and set it to its state variable. However, when I console log it, it gives me an empty string, which is the default value of it. If anyone could give me a suggestion or tell me what's wrong, that would be greatly appreciated. My briefly reproduced code snippet is down below:
const [userId, setUserId] = useState<string>("");
const getMyUserId = async () => {
const { data: objects } = await axios.get("/");
const user_id = objects.objects[0].id.toString();
setUserId(user_id);
console.log("userId", userId); <- output is empty string
};
const getMyCalendarId = async () => {
const url = `/${userId}/cal/calendars`;
const { data: objects } = await axios.get(`${url}`);
const calendar_id = objects.objects[0].id.toString();
setCalendarId(calendar_id);
};
useEffect(() => {
getMyUserId(); <- render every time page is loaded
getMyCalendarId
}, []);
To retrieve the user id you should access data, instead of objects. Like this:
const user_id = data.objects[0].id.toString();
objects is the typing of data, it is not the actual property.

Resources