Home > OS >  fetch() function to get one single post, from a post array
fetch() function to get one single post, from a post array

Time:10-17

I am following a tutorial and I wrote the following fetch() function when the instructor asked to try it on our own.

const API_URL = "http://localhost:3000/api/posts/";
const API_BASE_URL = "http://localhost:3000/";

window.onload = () => {
    getPost();
    getPostIdParam()
}

const getPostIdParam=()=>{
    const queryString= window.location.search;
    const urlParams=new URLSearchParams(queryString)
    return urlParams.get("id")
    console.log(urlParams)
}

const getPost = () => 
    {
        fetch(API_URL,{
            method:'GET'
        }).then((response)=>{
            return response.json()
        }).then((data)=>{
            buildPost(data)
        })
    }
    

const buildPost = (data) => {

    let postId=getPostIdParam()
    let post= data.find(x =>x.id == postId)
     console.log("post title"  JSON.stringify(post) )
     const postDate= new Date(parseInt(post.added_date)).toDateString()
     let postPrint=`
     <div id="individual-post-title">
            ${post.title}
     </div>
     <div id="individual-post-date">${postDate}</div>
     <div id="individual-post-content"> ${post.content}
     </div>
            `
            document.querySelector('.blog-inner').innerHTML
=postPrint


}

However the instructor's fetch() code look like this

window.onload = () => {
    getPost();
    getPostIdParam()
}

const getPostIdParam=()=>{
    const queryString= window.location.search;
    const urlParams=new URLSearchParams(queryString)
    return urlParams.get("id")
}

const getPost = () => 
    {

        const postId=getPostIdParam()
        const url=`${API_URL}${postId}`

        fetch(url,{
            method:'GET'
        }).then((response)=>{
            return response.json()
        }).then((data)=>{
            buildPost(data)
        })
    }

Why is fetch(API_URL) and fetch(url) both working? Shouldn't one be wrong?

CodePudding user response:

Your implementation is wrong as postId is needed for fetch =>

const url=${API_URL}${postId}

In instructor's code that is handled.

CodePudding user response:

What did you mean by both working? Actually, I assume both should work. It seems like the instructor's way is making more sense. Because the instructor was trying to get one particular post using the post id.

But your way which means using "http://localhost:3000/api/posts/" should ideally return all posts.

So I guess there are two endpoints already to fetch all posts and one particular post. Therefore, both URLs are working.

  • Related