Как добавить новый пост в список существующих?

Рейтинг: 0Ответов: 0Опубликовано: 18.04.2023

Как добавить новый пост в список существующих?

Как я понимаю, нужно сделать ререндер, но не могу сообразить, как именно.
Наверное что-то с .push().

const container = document.querySelector('.container');



    fetchAll()
    .then(responses => {
        const [users, posts] = responses;
        createPost(users, posts);
    })
    .catch(error => console.log(error));


    function createPost(users, posts) {
    console.log(users, posts);
    const wrapper = document.createElement('div');
    wrapper.classList.add('post');
    container.appendChild(wrapper);

    const slicedUsers = users.slice(0, 10);
    const slicedPosts = posts.slice(0, 10);

    slicedPosts.forEach((post, index) => {
        const user = slicedUsers[index];

        const postCard = document.createElement('div');
        postCard.classList.add('post__card');
        postCard.innerHTML = `
            <h2 class="post__title">${post.title}</h2>
            <p class="post__text">${post.body}</p>
            <p class="post__data-user">${user.name}</p>
            <p class="post__email">${user.email}</p>
        `;

        const deleteButton = document.createElement('button');
        deleteButton.innerText = 'Delete Post';
        deleteButton.setAttribute('data-id', post.id);

        deleteButton.addEventListener('click', () => {
            const postId = deleteButton.getAttribute('data-id');

            fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`, {
                method: 'DELETE',
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Ошибка удаления поста');
                    }
                    return response.json();
                })
                .then(data => {
                    slicedPosts.splice(index, 1);
                    postCard.remove();
                })
                .catch(error => {
                    console.error(error);
                });
        });

        postCard.appendChild(deleteButton);
        wrapper.appendChild(postCard);
    });
    }

    function addPostForm() {
    const createForm = document.createElement('form');
    createForm.classList.add('post__create-form');
    container.appendChild(createForm);

    const titleForm = document.createElement('h2');
    titleForm.classList.add('post__titleForm');
    titleForm.textContent = 'Add your post';
    createForm.appendChild(titleForm);

    const titleInput = document.createElement('input');
    titleInput.classList.add('post__input-title');
    createForm.appendChild(titleInput);
    titleInput.placeholder = 'Enter post title';
    titleInput.type = 'text';

    const bodyInput = document.createElement('input');
    bodyInput.classList.add('post__input-body');
    createForm.appendChild(bodyInput);
    bodyInput.placeholder = 'Enter post';
    bodyInput.type = 'text';

    const dataInput = document.createElement('input');
    dataInput.classList.add('post__input-data');
    createForm.appendChild(dataInput);
    dataInput.placeholder = 'Enter your full name';
    dataInput.type = 'text';

    const emailInput = document.createElement('input');
    emailInput.classList.add('post__input-email');
    createForm.appendChild(emailInput);
    emailInput.placeholder = 'Enter your email';
    emailInput.type = 'text';

    const addPostBtn = document.createElement('button');
    addPostBtn.textContent = 'Add post';
    addPostBtn.classList.add('post__submit');
    addPostBtn.type = 'submit';
    createForm.appendChild(addPostBtn);

    if (addPostBtn) {
        addPostBtn.addEventListener('click', e => {
            e.preventDefault();

            fetch('https://jsonplaceholder.typicode.com/posts', {
                method: 'POST',
                body: JSON.stringify({
                    title: titleInput.value,
                    body: bodyInput.value,
                    data: dataInput.value,
                    email: emailInput.value,
                    userId: 1,
                }),
                headers: {
                    'Content-type': 'application/json; charset=UTF-8',
                },
            })
                .then((response) => response.json())
                .then((json) => {
                    console.log(json);
                });
        });
    }
    }
addPostForm();

Ответы

Ответов пока нет.