I am making an e-commerce with React JS and use Firebase as a backend emulator. I've successfully created an order which stores the desired values and the doc is successfully stored in Firebase: the doc simulates the order which corresponds to what the client bought. I want to create a modal box which gives the buyer his order ID, however I can't capture that ID and don't know how to do it, but the console log does give me the ID.
Here is the code for creating the doc which goes to Firebase :
const saveOrder = async () => {
const cartFiltered = cart.map(({ id, title, quantity }) => ({ id, title, quantity }));
const orderToSave = {
buyer: buyer,
items: cartFiltered,
total: cartTotal(),
};
console.log(orderToSave);
const db = getFirestore();
const ordersCollection = collection(db, "orders");
const response = await addDoc(ordersCollection, orderToSave);
console.log(response.id);
}
And here is the code for the part of the modal which gives the ID :
<p> ("Your order ID is: {response.id} . Thanks for shopping!") </p>
I get the following error: "response is not defined".
The calls to Firestore all look fine to me at first glance, so more likely you're not making your response variable available to the UI rendering
To do that, you'll want to store the response in the state, for example by setting it up with a useState hook:
const [response, setResponse] = useState({ id: "" });
...
const res = await addDoc(ordersCollection, orderToSave)
setResponse(res);
console.log(res.id);