I am implementing a comment section. I am reading the data that is being saved in a database. However when reading the comments from an array of comments its giving issue on this line
const message_list =response.data.results.data.message.map((value) => (value));
Ive taken the code from this
https://riyanegi.github.io/react-comments-documentation/
axios.get( process.env.REACT_APP_API_URL +"product/" + this.product_id +"/idea/"+ this.idea_id +"/comment",{
headers: {
Authorization: "Bearer "+ user_access_token,
}})
.then(response => {
const message_list =response.data.results.data.message.map((value) => (value));
this.setState({ data: [...this.state.data, ...message_list] });
});
And then I am rendering:
render() {
return <CommentSection
currentUser={{
currentUserId: this.currentUser.user,
currentUserImg:
'https://ui-avatars.com/api/name='+this.currentUser.name+ '&background=random',
currentUserFullName: this.currentUser.name
}}
commentData={this.state.data}
onSubmitAction={(data) => this.onSubmitAction(data)}
onEditAction={(data) => this.onEditAction(data)}
onDeleteAction={(data) => this.onDeleteAction(data)}
customNoComment={() => this.customNoComment()}
onReplyAction = {(data)=>this.onReplyAction(data)}
/>
}
Based on the console.log you provided, it appears that response.data.results.data may need to be just response.data. You can confirm this by checking the console output to ensure that message is a property on it, and results isn't.
In any case, if you examine the object in your console to find the message array that you're trying to map, you should be able to find your message array nested somewhere in there.
I try Simple method like that
useEffect(() => {
const filterMessages = currentChat.filter((item) => {
return item.message?.toLowerCase()?.includes(searchQuery.toLowerCase())
})
console.log({ filterMessages })
}, [searchQuery])
but it is not a effective solution. what is logic behind this type of problem.
Thanks in advance.
Click at this
I want to create button but I don't know how can I do it? Can anybody give me an example? I want it without packages
Here is a simple example with no modules (just discord.js) to create a simple button and reply on click:
const { Client, MessageActionRow, MessageButton } = require('discord.js')
// The code... (the client.on('message') or .on('interactionCreate'))
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId("simple-example") // It is better to have a unique ID for the buttons
.setLabel("Text diplayed on the button")
.setStyle('PRIMARY'), //PRIMARY, SECONDARY, ALERT or SUCCESS
);
// For interactions do like this:
interaction.reply({ content: "Super button below", components: [row] })
// For messages do like this:
message.reply({ content: "Super button below", components: [row] })
client.on('interactionCreate', interaction => {
if (interaction.isButton()) {
if (interaction.customId === "simple-example") {
interaction.reply('Button clicked !')
}
}
})
// Log in with the bot
I have built a chat using Firebase and ReactJS. I mainly followed their Firebase's web codelab at https://firebase.google.com/codelabs/firebase-web#1. However, I have gotten stuck on the image uploading functionality. Since I am using ReactJS, I have had to modify their plain JS code to match mine. I am able to save a message with a "loading" image url in Firestore, then, I successfully save the image that I want to ultimately show in the chat in Firebase Storage, and finally then I successfully retrieve its url from Storage and replace it with the url of the loading image in Firestore. The image does show in the chat, however, the loading image is not actually replaced but, instead, it remains in the chat when I want it to be completely replaced, obviously, so that the loading image is no longer there. Here's what I mean, in this image:
As you can see the loading image on top stayed on instead of being replaced by the image underneath it. I think it should be filtered out somehow before I save the new snapshot with the new image url. However, I can not figure out how to do it correctly. I tried to filter it out based on the url of the loading image which is saved locally but since it is saved as a base64 in Storage, it did not work. Neither did using the actual Base64 code as a way to filter it out. So, I need help to solve this issue. The codelab does not really specify this nor is it clear how they do it in their code which is in plain Javascript anyways and I use ReactJS so it may not be 100% suitable.
Here's, I believe, enough code to see what is going on. Let me know if you need more of it.
Here's how I send images to the Chat: (modeled on the Firebase codelab)
sendImageToChat () {
this.state.chatFiles.forEach((file) => {
firebase.firestore().collection('Chats')
.doc(this.state.uid)
.collection('Messages')
.add({
docId: this.state.docId,
imageUrl: loadingLogo,
timestamp: new Date(),
uid: this.state.uid,
name: this.state.displayName,
email: this.state.email
})
.catch((error) => {
this.setState({ writeError: error.message });
})
.then((messageRef) => {
// 2 - Upload the image to Cloud Storage.
const filePath = `users/${this.state.displayName}/${this.state.uid}/${moment().format("MMM Do YY")}/${uuidv4()}/${file.name}`
return firebase.storage().ref(filePath).put(file).then((fileSnapshot) => {
// 3 - Generate a public URL for the file.
return fileSnapshot.ref.getDownloadURL().then((url) => {
// 4 - Update the chat message placeholder with the image's URL.
return messageRef.update({
imageUrl: url,
storageUri: fileSnapshot.metadata.fullPath
});
});
});
}).catch(function(error) {
console.error('There was an error uploading a file to Cloud Storage:', error);
});
})
this.setState({
chatFiles: []
})
document.getElementById('file-1').value = "";
}
Here's how I, then, setState when the loading image is added and then when its url is modified: (Notice how I try to filter out the loadingLogo which is the loading image out of the state but it does not obviously work for the reason explained above).
startChat () {
document.getElementById("myForm").style.display = "block";
const ref = firebase.firestore().collection('Chats').doc(this.state.uid).collection('Messages');
const query = ref.orderBy('timestamp', 'desc').limit(10)
this.unsubFromMessages = query.onSnapshot((snapshot) => {
if (snapshot.empty) {
console.log('No matching documents.');
firebase.firestore().collection('Chats').doc(this.state.uid).
set({
name: this.state.displayName,
uid: this.state.uid,
email: this.state.email
}).then(console.log("info saved"))
.catch((error) => {
console.log("Error saving info to document: ", error);
});
}
snapshot.docChanges().reverse().forEach((change) => {
if (change.type === 'removed') {
console.log(change.doc.data().content)
} else if (change.type === 'added') {
this.setState(state => {
const messages = [...state.messages, {id: change.doc.id, body: change.doc.data()}]
return {
messages
}
})
setTimeout( this.scrollToBottom(), 2000)
} else if (change.type === 'modified') {
const filteredMessages = this.state.messages.filter(message => message.imageUrl !== loadingLogo)
console.log(filteredMessages)
this.setState(state => {
const messages = [...filteredMessages, {id: change.doc.id, body: change.doc.data()}]
return {
messages
}
})
setTimeout( this.scrollToBottom(), 2000)
}
});
}, (error) => {console.log(error)});
}
This is part of the Chat's JSX:
<div className="chatArea" id='messages'>
{
this.state.messages.map((message, index) => {
return message.body.uid === this.state.uid
?
<div>
{
message.body.imageUrl ?
<img src={message.body.imageUrl} className="message-sent"></img>
:
<p className="message-sent" key={index}>{message.body.content}</p>
}
</div>
:
<p className="message-received" key={index}>{message.body.content}</p>
})
}
<div style={{ float:"left", clear: "both" }}
ref={(el) => { this.myRef = el; }}>
</div>
</div>
I know the issue is not with Firebase but rather with ReactJS. I know I need to remove, filter out, replace or delete that loading image before or after the modified message with the new url is saved to the state. So, please help me figure this out. I am sure many people may encounter this problem.
Thank you!
I figured it out. I might as well delete this question but it may help someone build a chat with ReactJS and Firebase. Anyways, my approach to filter out based on the object property, imageUrl is a viable option. It works! My silly oversight was that I did not add the parent property or object, "body", after the object "message". More specifically, instead of const filteredMessages = this.state.messages.filter(message => message.imageUrl !== loadingLogo), it should be const filteredMessages = this.state.messages.filter(message => message.body.imageUrl !== loadingLogo). You can also try to add an object property that you can use to filter out messages with, for example, allowed: yes or no. If you need more clarification, just ask me, I am glad to help. Happy coding!
I wish to use Or any Material-UI feedback component to capture the submit progress of the form
const onSubmit = (e) => {
e.preventDefault();
if (eventImage) {
const uploadImage = storage.ref(`EventImages/${values.eventName}`)
uploadImage.put(eventImage).then(() => {
storage.ref('EventImages').child(values.eventName).getDownloadURL().then(url => {
dbref.add({
eventName: values.eventName,
eventVenue: values.eventVenue,
eventAddress: values.eventAddress,
eventCategory: values.eventCategory,
eventOrganizer: values.eventOrganizer,
eventPhone: values.eventPhone,
eventEmail: values.eventEmail,
eventDetails: values.eventDetails,
eventDate: selectedDate.toDateString(),
eventTime: selectedDate.toLocaleTimeString(),
eventImgUrl: url
}).then((docRef) => {
console.log("Document written with ID: ", docRef.id);
setValues("");
setImg("");
setImgName("");
}).catch((error) => {
console.error("Error adding document: ", error);
});
})
})
}
}
I wish to use any Material-UI feedback component to achieve this
Typically a progress bar is used in such situations, so that the user knows how much of the task is completed/remains.
IMO showing a percentage completed and/or time remaining is helpful to. (time is a bit harder to implement)
Material UI Progress Bar : https://material-ui.com/components/progress/#linear-buffer
This might help?
They have an example attached with source code as well. Let me know if you need more info