简体   繁体   中英

React Fetch API + WordPress REST API Localhost Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'posts')

Hello to everyone who reads this and can help me out. So I am working on a personal project on a quest to learn ReactJS and my website used to just be a WordPress site. Now I want to use React as my frontend and WordPress as my backend, however, I get this annoying error and I swear I've spent days googling various error messages as they popped up and solved a few but this latest one just won't go.

I'm not sure if it's something to do with my local setup or just that the variable being fetched (an array of posts) is undefined. I am using the AJAX and Fetch API tutorial from the React documentation cause I like how they did it, but it doesn't seem to work with passing the values into the array for some reason.

I will post my code blow:

Home.js Component:

import React, { useEffect, useState } from 'react';
import Navigation from './Navigation';

class Home extends React.Component {

    constructor (props) {
        super (props);

        this.state = {
            error: null,
            postsLoaded: false,
            posts: []
        };
    }

    componentDidMount() {
        const wordPressSiteURL = 'http://localhost/wordpress';
        const postsEndpoint = '/wp-json/wp/v2/posts';
        const endpoint = wordPressSiteURL + postsEndpoint;

        fetch(endpoint)
            .then(response => response.json())
            .then(response => console.log('Our response being converted to JSON ', response))
            .then(result => console.log('The results of our response ', result))
            .then(
                (result) => {
                    this.setState({
                        postsLoaded: true,
                        posts: result.posts
                    });
                },
                (error) => {
                    this.setState({
                        postsLoaded: true,
                        error
                    });
                }
            )
    }

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

        // console.log('This state ', this.state);
        // console.log('Check for errors ', error);
        // console.log('Initial posts array values ', posts);
        
        if (error) {
            return <><Navigation /><div>Error: {error.message}</div></>;
        } else if (!postsLoaded) {
            return <><Navigation /><div>Loading...</div></>;
        } else {
            return (
                <div>
                    <Navigation/>
                    
                    <ul>
                        {posts && posts.map((post) => (
                            <li key={post.id}>
                                {post.content}
                            </li>
                        ))}
                    </ul>
                </div>
            );
        }
    }
    
}

export default Home;

App.js Page:

import React from 'react';
import Home from './components/Home';
import './App.css';

class App extends React.Component {
  render() {
    return (
      <div className='App'>
        <Home/>
      </div>
    );
  }
}

export default App;

Error Message: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'posts') at fetch.then.then.then.then.setState.postsLoaded (Home.js:68:1)

My other error message that "appears" to be fixed: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'map')

I am so annoyed I tried more than a dozen ways of fetching the posts array from my local WordPress REST API and in the return section changing how I was mapping over my posts.

When I made this change the specific map error went away:

<ul>
    {posts && posts.map((post) => (
        <li key={post.id}>
            {post.content}
        </li>
    ))}
</ul>

Instead of just posts.map, I put the "posts && posts.map" in to enforce some type of check before the array is mapped over. I would really appreciate help from someone who understands this error message and working with React specifically.

Don't use multiple then, as I saw in your code you used multiple then in the fetch call. look at the below code for your fetch call.

 fetch(endpoint)
            .then(response => response.json())
            .then(
                (result) => {
                   console.log('Our response being converted to JSON ', result)
                   console.log('The results of our response ', result)
                    this.setState({
                        postsLoaded: true,
                        posts: result.posts
                    });
                },
                (error) => {
                    this.setState({
                        postsLoaded: true,
                        error
                    });
                }
            )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM