Search code examples
reactjsfetchundefinedtypeerrorwordpress-rest-api

Fetching 'title' from WP REST API with React


I'm trying to fetch some data from the Wordpress REST API to render it in my React App. For example 'title', 'date' and 'content'. Here is my code:

class App extends React.Component {

  constructor (props){
   super(props);

   this.state = {
     title: {},
     date: "",
     content: {}
   };
 }

 componentDidMount() {
       return fetch(`https://example.com/wp-json/wp/v2/posts?per_page=100`)
       .then((response) => response.json())
       .then((responseJson) => {
         const { title, date, content } = responseJson;
         this.setState({ title, date, content });
       })
       .catch((error) => {
         console.error(error);
       });
 }

 render() {
   return (
      <div>
        <h1> {this.state.title.rendered} </h1>
        <h3> {this.state.date} </h3>
        <p> {this.state.content.rendered} </p>
      </div>
   );
 }
}

export default App;

But this gives me the following error for both 'title' and 'content':

TypeError: Cannot read property 'rendered' of undefined

What am I doing wrong here and how to fix this error?


Solution

  • This code fixed the issue:

    class App extends React.Component {
    
      constructor(props) {
        super(props)
        this.state = {
          posts: []
        };
      }
      componentDidMount () {
        return fetch('https://example.com/wp-json/wp/v2/posts?per_page=100')
        .then((response) => response.json())
        .then(posts => {
          this.setState({
            posts: posts,
          });
        })
      }
      render() {
        return (
          <div>
            <ul>
              {
                this.state.posts.map(item => (
                  <div key={item.id}>
                  <h1>
                      {item.title.rendered}
                  </h1>
                  <p dangerouslySetInnerHTML={{ __html: item.content.rendered }}>
                  </p>
                  </div>
                ))
              }
            </ul>
          </div>
        )
      }
    }
    
    export default App;