How can I display an object which I had pushed using react into firebase back in the screen? How could the objects in firebase be deleted? - reactjs

I'm very new to React and Firebase. I'm trying to display the object newData as mentioned in the code. I've pushed in a value but later it shows the error in the screen attached.
I'm creating a menu app so I want to add menu into the firebase and also in the mean time return the current menu as well. How could I return from the firebase? How can I update or delete the data already present in the object in firebase? Is there any way to access an object that I had uploaded before? Suppose I push a menu with dishes and price and then how could I delete it or update it. (each specific dish)
Image of the database is attached.
componentWillMount(){
/* Create reference to messages in Firebase Database */
let messagesRef = fire.database().ref('vendor/'+this.state.Day+'/'+this.state.Vendor+'/dishname').orderByKey().limitToLast(100);
messagesRef.on('child_added', snapshot => {
/* Update React state when message is added at Firebase Database */
let message1 = { text: snapshot.val(), id: snapshot.key };
this.setState({ messages: [message1].concat(this.state.messages) });
})
}
addMessage(e){
let messagesR = fire.database().ref('vendor/'+this.state.Day+'/'+this.state.Vendor+'/dishname').orderByKey().limitToLast(100);
messagesR.on('child_added', snapshot => {
/* Update React state when message is added at Firebase Database */
let message1 = { text: snapshot.val(), id: snapshot.key };
this.setState({ messages: [message1].concat(this.state.messages) });
})
var newData={
Type: this.inputE3.value,
Dish: this.inputEl.value,
Price : this.inputE2.value
}
fire.database().ref('vendor/'+this.state.Day+'/'+this.state.Vendor+'/dishname').push(newData);
this.inputEl.value = '';
this.inputE2.value = '';
this.inputE3.value = '';
}

Related

How to add a new element inside array then check if that element exists?

i have a get request that fetches data from my database to show on my website.
What i am trying to accomplish is when a new chat is created instead of refreshing the screen, i add it to the state set when the get request is completed.
when a new chat is created, it gets added to the list. Perfect
My problem is after the new chat is created and the user sends another message i am not able to find the new object added to the Array and so it also adds that the list and i get a error same id is used.
The problem occurs here:
if(records.some(e=>e['id']===msg.id)){
console.log("id exists")
var index = records.findIndex(x=>x.id===msg.id)
console.log(index)
let temp=[...records]
const recordMessages=temp[index].Messages
const newMessages=[msg,...recordMessages]
temp[index].Messages=newMessages
const lastMessage=temp[index].lastMessage
const newLastMessage=msg.message;
temp[index].lastMessage=newLastMessage;
setRecords(temp)
}else{
var index = records.findIndex(x=>x.id===msg.id)
console.log(index)
const newObject={
id:msg.id,
lastMessage:msg.message,
admin:msg.receiverId,
user:msg.senderId,
updatedAt:new Date(),
Messages:[msg]
}
const newRecord =records=>[newObject,...records]
setRecords(newRecord)
}
if(records.some(e=>e['id']===msg.id)){
the error occurs in this line of as it is not getting executed
also, here is my api call:
.get('/api/messages/',{headers:{"auth-token":localStorage.getItem('jwtToken')}})
.then(res => {
setRecords(res.data)
// console.log(records)
})
.catch(err =>
console.log(err)
)
if(records.some(e=>e['id']===msg.id)){
This is checking if the string 'id' is in the array. You want to pass in the variable id, which would be: if(records.some(e=>e.id === msg.id)){

Stripe webhook checkout.session items to Supabase

Im using next.js and Stripe webhooks to insert checkout sessions to Supabase that will create a customer's order history. I'm able to get the information about the whole order written to a table called 'orders', but am wondering what the best way to add individual items within each checkout session to another table called 'order_items' is. This way I can map through main orders and then the children items. Appreciate any help provided. Here is what I have for getting orders associated with a customer:
const upsertOrderRecord = async (session: Stripe.Checkout.Session, customerId: string) => {
const { data: customerData, error: noCustomerError } = await supabaseAdmin
.from<Customer>('customers')
.select('id')
.eq('stripe_customer_id', customerId)
.single();
if (noCustomerError) throw noCustomerError;
const { id: uuid } = customerData || {};
const sessionData: Session = {
id: session.id,
amount_total: session.amount_total ?? undefined,
user_id: uuid ?? undefined
};
const { error } = await supabaseAdmin.from<Session>('orders').insert([sessionData], { upsert: true });
if (error) throw error;
console.log(`Product inserted/updated: ${session.id}`);
};
The Checkout Session object contains a line_items field which is a list of each item included in the purchase.
However this field is not included in the object by default, and therefore won't be a part of your webhook payload. Instead you'll need to make an API call in your webhook handle to retrieve the Checkout Session object, passing the expand parameter to include the line_items field:
const session = await stripe.checkout.sessions.retrieve('cs_test_xxx', {
expand: ['line_items']
});

firebase retrieving data issue after database has updated in react js

here my DB is writing correctly and retrieving that data onto web but once there is an update in the DB the updated data are not shown in web..the old data are still shown..but once i refresh the page the updated values are shown any idea to fix this issue?
this is my retrieve data code
componentDidMount() {
this.authListener();
this.retrieveData();
console.log("Data loaded");
}
retrieveData = () => {
fire.auth().onAuthStateChanged(user => {
if (user) {
var ref = fire
.database()
.ref("data")
.limitToLast(1);
//takes the last data in DB
var userUID = fire.auth().currentUser.uid;
var query = ref.orderByChild("ID").equalTo(userUID); //retrieves data about only the current logged in user
console.log(userUID);
query.once("value", snapshot => {
let currentState = this.state.people;
const currentUser = snapshot.val();
for (let i in currentUser) {
currentState.push({
email: currentUser[i].UserEmail,
UserAnswer: currentUser[i].UserAnswer,
Questions: currentUser[i].Question,
id: currentUser[i].ID,
Score: currentUser[i].Score,
levelRook: currentUser[i].UserLevel,
levelStudent: currentUser[i].UserLevelStudent,
levelIntermediate: currentUser[i].UserLevelIntermediate,
levelExpert: currentUser[i].UserLevelExpert,
levelMaster: currentUser[i].UserLevelMaster,
rank: currentUser[i].RankValue
});
}
// currentState.push(user);
console.log(currentState);
this.rankData(); //setting rank value from DB
this.setState({
people: currentState,
dataHasLoaded: true
});
});
} else {
console.log("no user");
}
});
};
the issue is when the DB values are updated the above function is not called again to fetch the latest data ...any help on this?
I would imagine you need to look into Firebase database triggers. If you are asking the view to update when your database is updated outside of you application code.
Documentation: https://firebase.google.com/docs/functions/database-events

Get ID element from url and store it in a session array every time page loads

In reactjs, I am trying to store the id to session storage array which comes from URL, for example, http://localhost:3000/#/carnivallist/171 what's the solution to store all the ids?
I can only store one id. when the page refreshes the id is getting replaced on the session storage.
componentDidMount() {
if(this.props.params.id) {
let pro_id=[this.props.params.id];
console.log(pro_id);
console.log("otem");
let items=sessionStorage.getItem("carnival_dones");
console.log(items);
if(items!=""){
this.setState({ carnival_done: [...this.state.carnival_done,{carnival_done:pro_id}]});
}else{
this.setState({carnival_done:pro_id});
}
}
}
I expect to get all ids in an array but the session storage stores only the last value get saved. and the value not accessible through the session get method
You would have to save an array, something like below code:
let items = JSON.parse(sessionStorage.getItem("carnival_dones"));
if(!items){
items = []
}
items.push(this.state.carnival_done)
sessionStorage.setItem("carnival_dones",items);
Try saving array as json and parse it when retrieving.
componentDidMount()
{
if(this.props.params.id)
{
let pro_id = this.props.params.id;
let items = JSON.parse(sessionStorage.getItem("carnival_dones"));
if(items)
{
this.setState({ carnival_done: [...this.state.carnival_done, pro_id]});
}
else
{
this.setState({carnival_done: [pro_id]});
}
}
}
// Save session
save = () =>
{
sessionStorage.setItem("carnival_dones", JSON.parse(this.state.carnival_done));
}
The problem was I was using the
componentDidMount method instead of using componentWillMount so I found a solution changing the hook
componentWillMount() {
if(this.props.params.id) {
let pro_id=[this.props.params.id];
console.log(pro_id);
console.log("otem");
let items=sessionStorage.getItem("carnival_dones");
console.log(items);
if(items!=null){
this.setState({carnival_done:[...this.state.carnival_done,[items,pro_id]]});
//this.setState({ carnival_done: [...this.state.carnival_done,pro_id]});
console.log(this.state.carnival_done);
}else{
this.setState({carnival_done:[pro_id]});
}
}
}
Thank you so much for your support

react-native-gifted-chat showing same message multiple time

I'm using react-native-gifted-chat in my react-native app. As I shown in this image, there is same message displayed multiple time and message: Yes getting new msg 's place is also varied from it's actual position.
My issue is same as this. Can anyone please help me to solve this.
Thank you in advance.
I got a solution of my question. #Ron you are right but in my case the issue is different. I solved it by change my format of parameters. It took different format and I passed different so they conflicted each other. Here is the solution it may useful to others.
parse = snapshot => {
const { timestamp: numberStamp, text } = snapshot.val();
const { key: _id } = snapshot;
const createdAt = moment(snapshot.val().createdAt, "DD/MM/YYYY hh:mm:ss");
const user = { };
var temp_data = snapshot.val()
if(snapshot.val().name == this.state.temp_logged_name) {
user._id = 1;
user.name = temp_data.name;
user.avatar = temp_data.avatar;
}
const message = {
_id,
createdAt,
text,
user,
};
return message;
};
I had encountered this issue as well. I had set up react-native-gifted-chat on my mobile app. And at the other end I had set up a simple HTML page with a script to initialise the Websocket connection and send messages on the onsend event. What I had realised later that while the unique id was getting generated at the app end (because the id was being generated by the library itself), nothing of such sort existed at the other end.
Basically, this weird behaviour crops up when a unique id _id is missing for a message. Each message must have at least the following properties while executing GiftedChat.append(previousMessages, messages).
{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 2
}
}
There could be two reasons behind it,
1) Each message should be passed a unique id, so just use uuidv4 npm package and append it to _id prop of the object.
Example:
messages: GiftedChat.append(previousState.messages, {
_id: uuidv4(), // or use Math.round(Math.random() * 1000000)
text: text,
createdAt: new Date(),
user: {
_id: 2,
name: "React Native",
avatar: "https://placeimg.com/140/140/any"
},
image: attachment
})
2) Second possibility could be on the gateway you are using to initiate the chat between users. So, some gateways have known issues to repeat the message multiple times. You could to string comparison each time a new message is received and pushed to the chat screen, however it is not advised to do this.
I figured this out by simply applying the filter to the incoming message in useLayout Effect:
useLayoutEffect(() => {
db.collection('Chats').doc(docID).collection('messages').orderBy("createdAt", "desc").onSnapshot(snapshot => {
setMessages(
prev =>
prev
.filter((ftr,index,self) => ftr?.user?._id !== loginUser?.id) //login user id is the current user's id you can do the same for recieved messages
.concat
(snapshot.docs.map(doc => doc.data({
_id: doc?.id,
user: doc.data().user,
text: doc.data().text,
createdAt:new Date(doc.data().createdAt),
})
))
)
})
},[])
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Resources