Search code examples
wordpressreactjsaxioswordpress-rest-api

React Axios better way to get single post from WordPress REST


I'm using the following to fetch a single post from the WordPress REST API.

import React, { Component } from 'react';
import axios from 'axios';

class Post extends Component {

    constructor() {
    super();
    this.state = {
      post: [],
    };
  }

  componentDidMount() { 
    axios.get('http://example.com/wp-json/wp/v2/posts?slug=some-post')
    .then(response => {
      this.setState({ post: response.data });
    })
    .catch(error => {
        console.log(error);
    });
    }

  render() {
    return (

      <div>
        {this.state.post.map(single => {
            return(
            <div>
              <h1>{single.title.rendered}</h1>
              <p>{single.content.rendered}</p>
            </div>                                        
            );
        })}
      </div>
    );
  }
}

export default Post;

Is there a better/more straightforward way to render the post without mapping an array?


Solution

  • If api returns array then you can take only first element, f.e.:

    this.setState({ post: response.data[0] });
    

    Of course you should use then some conditional rendering (map works with empty array):

    if(!this.state.post) return <Loading />