0

I'm trying to fetch this JSON in my javaScript code using the fetch API:

{
    "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
    ]
}

This is my code:

const endpoint = 'http://localhost:3000/posts'

let posts = []

fetch(endpoint)
    .then(resp => resp.json())
    .then(data => posts.push(...data))


console.log(posts[0])

The console.log gives me undefined on chrome's console, but if I type posts[0] on the same console I get the post object I'm hoping to get.

I'm serving the JSON file with json-server and the .html with the vs code extension live-server.

Ivan
  • 51
  • 9
  • *"I'm trying to fetch this JSON..."* That JSON is invalid. It's the *inside* of an object initializer, but it needs the outside of it (the `{}`, e.g. `{"posts: [...]}`). – T.J. Crowder Aug 13 '18 at 12:22
  • However, the main issue here is that `fetch` is *asynchronous*, so `posts` is still empty as of when you log it (*later*, when the fetch completes, entries will be added to it). Also note that you're not checking `.ok`, which you need to do; details in [this post on my anemic little blog](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html). – T.J. Crowder Aug 13 '18 at 12:23
  • The `console.log` statement is executed before `.then(data => posts.push(...data))`, you should learn about how async functions work. – Titus Aug 13 '18 at 12:23
  • 1
    Thank you @T.J.Crowder , great post. – Ivan Aug 13 '18 at 12:45

0 Answers0