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)
)