HUGO
HUGO

Reputation: 1

Cannot read property 'map' of undefined (Trying to fetch from API)

I'm fairly new to ReactJS and the API fetching thing and I've been stuck on this error for a long time so I wonder if anybody knows what the problem is :P

I'm trying to fetch a json file and then extract some data from it. The API is https://hytale.com/api/blog/post/published but they dont have CORS enabled so I'm trying to use a CORS proxy called allorigins. Thanks!

Code:

import React from "react";
import BlogPost from "./BlogPost";

class BlogPosts extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [],
    };
  }

  componentDidMount() {
    fetch(
      `https://api.allorigins.win/raw?url=https://hytale.com/api/blog/post/published`
    )
      .then((response) => {
        if (response.ok) {
          console.log(response);
          response.json();
          console.log("Blogposts fetched PHASE 1!");
        }
      })
      .then((jsonData) => {
        this.setState({ posts: jsonData });
        console.log(this.state.posts);
        console.log(jsonData);
        console.log("Blogposts fetched PHASE 2!");
      });
  }

  render() {
      return (
        <div className="bg-gray-100 py-5 px-8 rounded-xl w-auto my-8 shadow-lg">
          <div className="text-3xl font-semibold">
            Latest BlogPosts or Announcements
          </div>
          <span className="inline-block my-3 mr-2 bg-green-100 px-3 py-1 rounded-2xl text-green-700">
            <b className="text-green-800">0</b> new blogposts in the last month.
          </span>
          <br />
          <p className="font-semibold text-xl mb-5 text-gray-700">
            Check out the latest 5 blogposts here:
          </p>

          {this.state.posts === null ? (
            <span className="text-gray-400 font-semibold text-lg">
              Loading BlogPosts...
            </span>
          ) : (
            this.state.posts.map((post) => {
              return <BlogPost
                name={post.title}
                date={post.publishedAt}
                author={post.author}
                type={post.coverImage.contentType}
                image={
                  "https://cdn.hytale.com/variants/blog_thumb_" + post.coverImage.s3Key
                }
                text={post.bodyExcerpt}
                link="https://hytale.com/news/2020/12/december-2020-development-update"
              />
              })
          )}
        </div>
      );
  }
}

export default BlogPosts;

Upvotes: 0

Views: 108

Answers (1)

Brian Thompson
Brian Thompson

Reputation: 14395

You need to return the JSON from the first then() callback.

.then((response) => {
  if (response.ok) {
    return response.json();
  }
})

Failure to do so is leading to jsonData being undefined in the next callback.

The MDN docs have a nice simple example on fetching JSON here. They use an implicit return for a shorter syntax, but they are returning the result of the .json() call.

Upvotes: 2

Related Questions