how can I show time like whatsApp chat - javascript

I build chat application using firestore as backend. Now I want when some user send a message there should be a time of that message.
there is some error ie.
react-dom.development.js:14887 Uncaught Error: Objects are not valid as a React child (found: object with keys {seconds, nanoseconds}). If you meant to render a collection of children, use an array instead. at throwOnInvalidObjectType (react-dom.development.js:14887:1)
react_devtools_backend.js:4012 The above error occurred in the component:
I wrote this code to send data on firebase
messages: arrayUnion({
id: uuid(),
text,
img: downloadURL,
senderId: currentUser.uid,
date: Timestamp.now(),
// time: Date().get
});
and when a fetch data from firebase
<div>
<p>
{message.text}
<span>{message.date && <span>{message.date}</span>}</span>
</p>
{message.img && <img src={message.img} alt="" />}
</div>;
I want to show message time with message.
Note: I map through messages like :
messages.map(message => {})

Note: Edited
In your original code, you have:
message.date && <span>{message.date}</span>
But according to the error message, message.date is a JavaScript object which React does not know how to display. If your message object comes directly from Firestore, message.date would be a JavaScript object that looks something like this:
{
nanoseconds: <something>,
// some other Timestamp properties
}
React does not know how to display this. Thus, try turning message.date into a string and then displaying it. This could involve many methods depending on how you want to implement it and format the final string. Many ways are provided in How do I convert a Firestore date/Timestamp to a JS Date()? when accessing the time.

Related

FirebaseError: Function setDoc() called with invalid data. Unsupported field value: undefined

OrderDetails Logged image
I want to save order details to my firestore db,Here my orderDetails:
const orderDetails=[{
id:"ID1",
name:"foo"
},
{
id:"ID2",
name:"foo-foo"
},
]
Here is the code for adding this order Details to fire store:
.then(({paymentIntent})=>{
if(user){
console.log(basket);
const userRef=doc(db,'shopDB',user.uid);
const userOrderRef=doc(userRef,'userOrderInfo',paymentIntent.id);
setDoc(userOrderRef,{
orders: basket,
created :paymentIntent.created,
amount :paymentIntent.amount
},{merge:true})
Here all working if i set document without orderDetails,Other two values will added to fire store,but when i try to add orders to database it throws error
error>>>>>>>>>>>
FirebaseError: Function setDoc()
called with invalid data. Unsupported
field value: undefined
Can anyone help me with this?
looks like 1 of the 2 missing:
orderDetails is undefined
userOrderRef is undefined
try printing them both to make sure what's missing there
Edit:
now that I can see your console.log, your issue is with field alternative:undefined at element in index 1 according to your photo.
remove this property before trying to save it on firestore

How to decode transaction input data using `ethers.utils.defaultAbiCoder`

I'm fetching transaction data using Etherscan API. This is the example result I'm getting:
{
blockNumber: '7409930',
timeStamp: '1639151980',
hash: '...',
nonce: '4124',
...
input: '0x9d90e4c8000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000002000000000000000000000000093238bb66b5d15b4152c5db574e3397ff1b1a450',
contractAddress: '',
cumulativeGasUsed: '403775',
gasUsed: '1162315',
confirmations: '191308'
}
I now need to figure out the event type (contract method, e.g. TransferOwnership, stakeTokens,...) for this transaction. This data is stored in input property of this object.
I managed to accomplish this using abi-decoder library, but I want to accomplish the same thing using ethers's utility method (whichever).
My current implementation:
const abiDecoder = require("abi-decoder");
abiDecoder.addABI(contractAbi);
// "item" is transaction data, input property is encoded stuff from which I want to get the contract method used by this transaction
const decodedInput = abiDecoder.decodeMethod(item.input);
// contract method
console.log(decodedInput.name);
I was reading through ether's documentation (https://docs.ethers.io/v5/api/utils/abi/coder/), but I can't figure it out.
you can try what is recommended in this: https://github.com/ethers-io/ethers.js/issues/423 . but if you are interacting with BSC, this is not possible due to the error input data too big causing Error in Big Number Number can only safely store up to 53 bits

MongoDB _id returns undefined on frontend (VueJS)

I created a simple fullstack webapp using NodeJS & Express + MongoDB to build the backend API and Vue.JS for the frontend.
All the Write Read and Delete API worked perfectly (I tested it using Postman). Everything works perfectly as well on the frontend, except when I tried to iterate (v-for) on an array of objects to get the _id, it doesn't work.
The array called posts has the attributes of 'text' and 'createdAt'. The v-for works perfectly and output the 2 attributes as expected. However, I tried to output _id (default id from MongoDB) but it returned "undefined".
This causes a problem because if I can't get _id, it wouldn't be possible for me to delete a specific post using the existing backend delete API.
From my understanding, in the backend side, the _id needs to be converted into ObjectId first before it can be used for db querying. But on the frontend (vue) I am not sure on how can turn _id into ObjectId. Am I getting into the right direction here?
<div class="post" v-for="(post,i) in posts " :key="post._id" :index="i" :item="post" #dblclick="deletePost(post._id)">
{{post.createdAt.getDate()}}/{{post.createdAt.getMonth() + 1}}/{{post.createdAt.getFullYear()}}
<p class="text">{{post.text}}</p>
</div>
...
methods: {
async deletePost(id){
console.log(id) //this returns undefined
await PostService.deletePost(id);
this.posts = await PostService.getPosts();
}
},
...
//del post in PostService.js
static deletePost(id){
return axios.delete(url+id)
}
//backend delete api
router.delete('/:id',async (req,res)=>{
const posts = await loadPostCollection()
console.log(ObjectID(req.params.id))
await posts.deleteOne({_id: ObjectID(req.params.id)});
res.status(200).send()
})
expected output: _id of each 'post', e.g:5cfa8c29f74c65ae485a6d93
actual output: undefined
no error message(s).
You need to add the property reference post, like this:
<div class="post" v-for="(post,i) in posts " :key="post._id" :post="post" #dblclick="deletePost(post._id)">
{{post.createdAt.getDate()}}/{{post.createdAt.getMonth() + 1}}/{{post.createdAt.getFullYear()}}
<p class="text">{{post.text}}</p>
</div>
You don't have to convert _id to Mongo ObjectID on the FrontEND.
Your code looks normal, send all post object to function like that and debug it.
#dblclick="deletePost(post)"
Probably your backend return _id as an object.

How to remove <br> tags from string in GraphQL query results

I'm working on a React application that utilizes Apollo and GraphQl to query an external API. My issue is that the data contains strings that have tags in them. I'd like to remove the tags.
The string looks like:
Additionally, Igor works as a driver for a transport company.<br /><br />The spring agricultural works on the land started already and he now supports more expenses.
My response data looks like 'data.loans.lend.values', and so I've tried using the str.replace() method on my data. However, it didn't work. I've probably spent about five hours combing through the web to find a solution, but haven't been able to.
This is what my Apollo query component looks like.
<Query query={kivaLoans} variables={{ country: country, sortBy: sort, limit: limitResults }}>
{({ data, loading, error }) => {
if (loading) return <div><p>Loading...</p></div>;
if (error) return <p>ERROR</p>;
return (
And this is my GraphQL query.
gql`
query ($country: [String], $sortBy: LoanSearchSortByEnum, $limit: Int) {
lend {
loans(filters: {status: fundraising, country: $country}, sortBy: $sortBy, limit: $limit) {
values {
id
plannedExpirationDate
image {
url(customSize: "s900")
}
name
loanFundraisingInfo {
fundedAmount
}
loanAmount
description
loanAmount
}
}
}
}`
Has anyone else encountered this issue before?
if you are receiving data back in a format you don't like, this means the graphql server, a database it leverages, or an api it leverages, is returning data to the graphql server in a format that isn't useful for you. The other possibility is that your server itself is formatting your data in an annoying way. So here are your options:
change your server / data sources as appropriate
do a global replace on the string returned: str.replace(/<b>/g, '').replace(/<\/b>/g, ''). Double check my escape characters, I may have that backwards.
in a string replace, /[what you want replaced]/g = a regex for global detection, across the entire string

In node.js how to extract uid from returned facebook providerData json array?

I've got my users signing in with facebook and that gets stored in firebase auth. In index.js i've got an onCreate function that stores some facebook related data in firestore.
When i log to cloud functions console event.data.providerData I get this:
[ { displayName: 'xxxx xxxxx',
photoURL: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p100x100/xxxxxxxxx_439xxx336xxxxxx.jpg?oh=bcxxxxxxxxxxx431ce&oe=xxxx4xxx3',
providerId: 'facebook.com',
uid: 'xxxxx725xxxxxx80' } ]
In my index.js file i've set this as
const providerData = event.data.providerData;
This always confuses me and i've read about it a lot.
These are my questions:
Is this a javascript object? Or a JSON object? Or a JSON array?
Does this need to be parsed? eg. JSON.parse(event.data.providerData)? What is JSON.parse actually doing?
To get access to the uid I have tried:
providerData[3]
providerData.uid
providerData["uid"]
providerData['uid']
JSON.parse(providerData) - and then all the above again
var obj = JSON.parse(providerData);
console.log( obj.uid );
I know there are plenty of posts out there re: similar topics and I think i've read a lot of them.
Thanks.
It's an array containing a JSON object at index 0.
The javascript interpreter is automatically parsing Valid JSON as a Javascript object.
Knowing that, you can now access directly the properties of your object like this:
providerData[0].displayName
providerData[0].photoURL
providerData[0].providerId
providerData[0].uid // <-- Your use case

Categories

Resources