In my Angular app, I am storing an array of Message objects within a Conversation object.
I was able to add a new Message to a hard-coded Conversation with the below code:
private _conversations = new BehaviorSubject<Conversation[]>([]);
get conversations() {
return this._conversations.asObservable();
}
addMessageToConversation(conversationId: string, message: string) {
return this.conversations.pipe(
take(1),
tap(conversations => {
const updatedConversationIndex = conversations.findIndex(convo => convo.id === conversationId);
const updatedConversations = [...conversations];
const convoToUpdate = updatedConversations[updatedConversationIndex];
convoToUpdate.messages.push(
new Message(
Math.random().toString(),
message,
)
);
this._conversations.next(updatedConversations);
})
);
}
I made the below changes to this method so that I could update the object in a Firebase DB:
addMessageToConversation(conversationId: string, message: string) {
let updatedConversations: Conversation[];
return this.conversations.pipe(
take(1), switchMap(conversations => {
console.log(conversations);
const updatedConversationIndex = conversations.findIndex(convo => convo.id === conversationId);
updatedConversations = [...conversations];
const convoToUpdate = updatedConversations[updatedConversationIndex];
convoToUpdate.messages.push(
new Message(
Math.random().toString(),
message,
)
);
return this.http.put(
`myUrl/conversations/${conversationId}.json`,
{ ...convoToUpdate, id: null }
);
}), tap(() => {
this._conversations.next(updatedConversations);
})
);
}
But now when I call this method, I get this console error:
conversations.findIndex is not a function
This error is in relation to this line of code:
const updatedConversationIndex = conversations.findIndex(convo => convo.id === conversationId);
Also, when I console.log(conversations) inside switchMap, this is logged:
{id: "-M52u0Fwdt5a9xE0wwCk", userId: "user3", mechanicId: "user2", messages: Array(1)}
Can someone please tell me why this is happening, & what changes are required to get it working?
findIndexworks for array only, check developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/….