It seems that the issue you're experiencing is due to the way your actualizarListaConversaciones function is handling the update of the conversation list when the sender sends a message. Let's walk through what's happening:
Problem Explanation:
- When a message is received by the user (i.e., they are the receiver), the conversation list updates correctly because the conversation already exists in the list, and your function successfully updates the existing conversation item.
- However, when the user sends a message to someone (i.e., they are the sender), if there isn't already a conversation item in the list for that recipient, the
actualizarListaConversaciones function doesn't find an existing conversation to update. As a result, the conversation list doesn't update to reflect the new message.
Reason:
- Your
actualizarListaConversaciones function is designed to update existing conversation items, but it doesn't handle the case where a conversation doesn't already exist in the list.
- When the sender sends a message to a new recipient, there's no conversation item in the DOM with a
data-receptor attribute matching the recipient's user ID. Therefore, the function can't update anything.
Solution:
You need to modify your actualizarListaConversaciones function to handle the case where the conversation does not yet exist in the conversation list. If the conversation isn't found (i.e., conversacionActualizada is false), you should create a new conversation item and add it to the list.
Here's how you can modify your function:
-
Check if the conversation exists:
- After iterating over the existing conversation items, if
conversacionActualizada is still false, it means the conversation doesn't exist in the list.
-
Create a new conversation item:
- Create a new
<li> element with the necessary classes and attributes (data-receptor, etc.).
- Populate it with the required HTML structure, including the profile image, message preview, and timestamp.
-
Append the new conversation item to the conversation list:
- Add the new
<li> element to the .mensajes <ul>.
-
Ensure you have the necessary data to create the new item:
- You may need additional information such as the recipient’s profile image URL, username, conversation ID, etc.
- This data can be sent along with the message data from the server or fetched via an API call when needed.
Modified actualizarListaConversaciones function:
function actualizarListaConversaciones(usuarioId, ultimoMensaje) {
const listaMensajes = document.querySelector('.mensajes');
const mensajesItems = listaMensajes.querySelectorAll('.mensaje');
let conversacionActualizada = false;
mensajesItems.forEach(mensaje => {
const receptorId = mensaje.getAttribute('data-receptor');
// Verifica si el receptor coincide con el id del usuario
if (receptorId == usuarioId) {
const vistaPrevia = mensaje.querySelector('.vistaPrevia p');
if (vistaPrevia) {
vistaPrevia.textContent = ultimoMensaje;
}
const fechaRelativa = formatearTiempoRelativo(new Date());
const tiempoMensaje = mensaje.querySelector('.tiempoMensaje span');
if (tiempoMensaje) {
tiempoMensaje.textContent = fechaRelativa;
}
conversacionActualizada = true;
}
});
if (!conversacionActualizada) {
// No se encontró una conversación existente, crear una nueva
// Necesitas tener datos adicionales para crear el nuevo elemento
// Por ejemplo, imagen de perfil, nombre, id de la conversación, etc.
// Supongamos que tienes una función obtenerDatosUsuario que devuelve una promesa con los datos del usuario
obtenerDatosUsuario(usuarioId).then(datosUsuario => {
const nuevoMensaje = document.createElement('li');
nuevoMensaje.classList.add('mensaje');
nuevoMensaje.setAttribute('data-receptor', usuarioId);
nuevoMensaje.setAttribute('data-conversacion', datosUsuario.conversacionId);
nuevoMensaje.innerHTML = `
<div class="imagenMensaje">
<img src="${datosUsuario.imagenPerfil}" alt="Imagen de perfil">
</div>
<div class="vistaPrevia">
<p>${ultimoMensaje}</p>
</div>
<div class="tiempoMensaje">
<span>${formatearTiempoRelativo(new Date())}</span>
</div>
`;
// Añadir el nuevo mensaje al principio de la lista
listaMensajes.prepend(nuevoMensaje);
}).catch(error => {
console.error('Error al obtener datos del usuario:', error);
});
}
}
Notes:
- Fetching Additional Data: The
obtenerDatosUsuario function is a placeholder for whatever method you use to get user data (e.g., an AJAX request to your server). Ensure you implement this function to return a promise that resolves with the necessary user data.
- Conversation ID: If you have a conversation ID, you should include it in the
data-conversacion attribute to maintain consistency.
- Handling Promises: Since fetching data is asynchronous, make sure your code correctly handles the promise with
.then() and .catch().
- Optimizations:
- If you already have the necessary data (e.g., you store user data in a JavaScript object), you don't need to fetch it from the server.
- Ensure that you handle potential errors when fetching data.
Alternative Solution:
If you prefer not to handle the creation of new conversation items on the client side, you can refresh the conversation list from the server whenever a new conversation is started:
if (!conversacionActualizada) {
// La conversación no existe, solicitar la lista actualizada al servidor
fetch('/ruta/al/endpoint/que/devuelve/conversaciones')
.then(response => response.text())
.then(html => {
// Reemplazar el contenido de la lista de conversaciones
document.querySelector('.bloqueConversaciones').innerHTML = html;
})
.catch(error => {
console.error('Error al actualizar la lista de conversaciones:', error);
});
}
Notes:
- Server Endpoint: Replace
'/ruta/al/endpoint/que/devuelve/conversaciones' with the actual URL to your server endpoint that returns the updated conversation list HTML.
- Partial HTML: Ensure that the server returns the HTML for the conversation list correctly.
- Performance Consideration: Fetching the entire conversation list might be less efficient than updating just one item, but it simplifies client-side code and ensures consistency.
Conclusion:
By modifying actualizarListaConversaciones to handle new conversations, you ensure that the conversation list stays up to date whether the user is sending or receiving messages. Make sure to test these changes thoroughly to handle edge cases and ensure a smooth user experience.