Home > Back-end >  Cannot read properties of undefined (reading 'data') on my React WP RestFul Api
Cannot read properties of undefined (reading 'data') on my React WP RestFul Api

Time:07-16

My code was working fine until i added a new blog post and I got this error on my console making my React Application goes blank. after looking around, I was unable to fix the issue.

bellow is my code:

import React from "react";
import { Link, NavLink } from "react-router-dom";
import axios from "axios";
import renderHTML from "react-render-html";
import Loader from "../img/loader.gif";
import { formatDistanceToNow } from 'date-fns';

   class Blog extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      posts: [],
      error: "",
    };
  }
  componentDidMount() {
    const wordPressSiteUrl = "https://my-api-site-address";
    this.setState({ loading: true }, () => {
      axios
        .get(`${wordPressSiteUrl}/wp-json/wp/v2/posts/?per_page=10`)
        .then((res) => {
          this.setState({ loading: false, posts: res.data });
        })
        .catch((error) =>
          this.setState({ loading: false, error: error.response.data.message })
        );
    })
  }

  render() {
    
    const { posts, loading , error } = this.state;

    return (
      <div>
        <main>
          <div id="heading">
            <h2>Latest News</h2>
          </div>

          {error && <div className="alert alert-danger">{error}</div>}


          {posts.length ? (
            <article>
              {posts.map((post) => (
                <div
                  key={post.id}
                  id="blogrow"
                  className="row"
                  style={{
                    backgroundColor: "rgb(50,52,54)",
                    marginBottom: "10px",
                    paddingBottom: "10px",
                  }}
                >
                  <div className="col-4 resize">
                    <img className="postimg"
                      src={post.better_featured_image.source_url}
                      style={{
                        borderRadius: "10px"
                      }}
                        alt="{post.title.rendered}"  
                    />
                  </div>
                  <div className="col-8 blogcol-8">
                    <h3 id="blogheadercss">
                      <Link to={`/posts/${post.id}`} dangerouslySetInnerHTML={{ __html: post.title.rendered}} style={{ color: "#FFC107" }}></Link>
                    </h3>
                    <p id="blogcontentcss">
                      {renderHTML(post.excerpt.rendered)}
                    </p>

                    <div className="col">
                      <div className="row mt">
                        <div className="col-lg-6 col-md-6 col-sm-6">
                          <button id="datetime" className="btn btn-outline-warning btn-sm">
                          { post.x_date }
                          </button>
                        </div>

                        <div className="col-lg-6 col-md-6 col-sm-6">
                          <div
                            id="readmore"
                            className="btn btn-outline-primary btn-sm"
                          >
                            <Link to={`/posts/${post.id}`} style={{ color: "white" }}>
                              Read More
                            </Link>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </article>
          ) : (
            ""
          )}

          { loading && <img className="loader" src={Loader} alt="Loading" /> }

        </main>
        <div
          className="container"
          style={{
            marginTop: "10px",
            paddingRight: "50px",
            textAlign: "right",
          }}
        >
          <button className="btn btn-outline-primary">
            <NavLink exact to="/blogs">
              Explore More
            </NavLink>
          </button>
        </div>
      </div>
    );
  }
}

export default Blog;

I will like to fix an error with auto fetch API every 5mins.

i will be glad if someone can work me through. Thanks

CodePudding user response:

There's a CORS preflight, basically if you make a request, it will send OPTIONS first

That's why the res will be undefined and res.data cannot be read So make a conditional first wherein it runs only if the res is not undefined

CodePudding user response:

the componentDidMount function should be modified like this

  componentDidMount() {
    const wordPressSiteUrl = "https://my-api-site-address";
    this.setState({ loading: true }, () => {
      axios
        .get(`${wordPressSiteUrl}/wp-json/wp/v2/posts/?per_page=10`)
        .then((res) => {
          if(res)
            this.setState({ loading: false, posts: res.data });
        })
        .catch((error) =>
          this.setState({ loading: false, error: error.response.data.message })
        );
    })
  }
  • Related