AJAX Posts Reverse Order After Refresh the Page When Multiple Posts are Created in the Same Minute from Same User

I'm working on a social network project using Django for the backend and JavaScript for the frontend. Users can post new content, and the global feed is updated both dynamically via Ajax and by refreshing the page.

Everything works fine, except when a user creates multiple posts within the same minute. Initially, the newest post is displayed at the top, but when I refresh the page, the order of posts gets reversed for that specific user, where older posts appear above newer ones.

I'm using the created_at field (with DateTimeField) to order the posts. Here's a snippet of the key code that handles fetching the global stream and updating the DOM:

function updateStream(posts) {
    const postContainer = document.querySelector('#post-list');

    posts.forEach(post => {
        let postElement = document.getElementById(`id_post_div_${post.post_id}`);

        if (!postElement) {
            postElement = document.createElement('div');
            postElement.id = `id_post_div_${post.post_id}`;
            postElement.className = 'post';
            postElement.innerHTML = `
                <p>
                    <strong><a href="/profile/${post.author_username}" id="id_post_profile_${post.post_id}" class="post-profile">
                        ${post.author}</a></strong>: 
                    <span id="id_post_text_${post.post_id}" class="post-txt">${sanitize(post.content)}</span>
                    <span id="id_post_date_time_${post.post_id}" class="post-date-time">${formatDate(post.created_at)}</span>
                </p>
                <div class="comments" id="comments_${post.post_id}"></div>
                <div id="id_comment_input_div_${post.post_id}" class="add-comment">
                    <input type="text" id="id_comment_input_text_${post.post_id}" placeholder="Add a comment" />
                    <button id="id_comment_button_${post.post_id}" onclick="addComment(${post.post_id})">Submit</button>
                </div>
            `;

            // Add new post to the correct position
            postContainer.appendChild(postElement);
        }
    });
}

What I’ve Tried:

Adding a fallback to sort by post_id when posts have the same created_at, but it didn’t seem to fix the issue completely. My Question: How can I ensure that new posts are always displayed at the top, even when multiple posts are created within the same minute?

Any suggestions or guidance on the proper way to handle this would be greatly appreciated!

Вернуться на верх