Using Fetch API Patch to add name/author to resources being pulled and displayed on webpage. Change is not displaying

Viewed 53

I’m working on a coding project for a potential job that requires me to pull data from a fake API (I have to use https://jsonplaceholder.typicode.com/) and display it on a webpage. The data that needs to show on the page is Title, Author, and body. I’ve managed to get the data to display on my page but there is no Author data in the API which means I need to add it. I used fetch patch to add Author to some of the resources and I see in the console that the change has been done but it won’t display on the webpage. I’ve been searching for hours for a solution and can’t seem to find one.

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="resources/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

   
    <title>Code Problem 4</title>
</head>
<body>
    <header><h1>Blog Post</h1></header>
    <div id="content">
        <h2>Posts</h2>
        <form class="search" action="action_page.php">
            <input type="text" placeholder="Filter by Author" name="search">
            <button type="submit"><i class="fa fa-search"></i></button>
          </form>
    </div>
    <script src="resources/javascript/script.js"></script>
</body>
<footer>
    <span class="shapes">&#9679; &#9652; &#9632;</span>
 </footer>
</html>
Promise.all([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20].map(id =>
    fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
        method:'PATCH',
        body: JSON.stringify({
            name: "CS Lewis",
    }),
    headers: {
        'Content-Type': 'application/json; charset=UTF-8'
    },
})
        .then((response) => response.json())))
        .then((json) => console.log(json));


function fetchData() {
    
    fetch('https://jsonplaceholder.typicode.com/posts/').then(response => {
        if (!response.ok) {
            throw Error('ERROR');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
        const html = data.map(posts => {
            return `
            <div class="post">    
                <p>Title: ${posts.title}</p>
                <p>Author: ${posts.name}</p>
                <p>Body: ${posts.body}</p>
            </div>`
        }).join(' ');
        console.log(html);
        document.querySelector('#content').insertAdjacentHTML('beforeend', html);
    })
    .catch(error => {
        console.log(error);
    })
}   
fetchData();

 
    
2 Answers

https://jsonplaceholder.typicode.com/posts/ is a mockapi. It only simulates to update the posts (returning you seemingly updated posts), but in reality it hasn't adjusted anything.

The next time you use fetchData, its data resets to the default mock data.

You can still access the name after the PATCH if you want to, e.g. like this:


Promise.all([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20].map(id =>
    fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
        method:'PATCH',
        body: JSON.stringify({
            name: "CS Lewis",
    }),
    headers: {
        'Content-Type': 'application/json; charset=UTF-8'
    },
})
        .then((response) => response.json())))
        //By adding this `then` section, you use the patch response its return data to populate your posts
        .then(data => {
           console.log(data);
           const html = data.map(posts => {
            return `
            <div class="post">    
                <p>Title: ${posts.title}</p>
                <p>Author: ${posts.name}</p>
                <p>Body: ${posts.body}</p>
            </div>`
           }).join(' ');
        console.log(html);
        document.querySelector('#content').insertAdjacentHTML('beforeend', html);
    })
;

codepen link

Your Promise.all is fetching the data, but then you're not doing anything with it. It just gets logged to the console and then thrown away. In your fetchData() function (where you actually need it), you are re-fetching the data again, without IDs and then not adding the name property.

Also PATCH isn't really the right tool for the job. It's intended for updating an API, which isn't what you're doing here.

Rather than trying to do that, you should instead just add the name to the JS array of objects that the JSON gets converted into.

const url = "https://jsonplaceholder.typicode.com/posts/";
const http = await fetch(url);
const response = await http.json();

for (const object of response) object.name = "CS Lewis";
Related