Search code examples
wordpressreact-nativefetch-apiwordpress-rest-apicreate-react-native-app

How do I use the `fetch()` function in React Native to retrieve posts from WordPress REST API?


I'm using the create-react-app to build an React Native app that would show a list posts from WordPress. I have a problem fetching the data from WordPress. I think I'm not fully understanding how the fetch() function works. This is what I have at the moment:

export default class Posts extends Component {
  constructor() {
    super();
    this.state = {
      posts: []
    }
  }
componentDidMount() {
    let dataURL = "http://localhost/wordpress/wp-json/wp/v2/posts";
    fetch(dataURL)
      .then(response => response.json())
      .then(response => {
        this.setState({
          posts: response
        })
      })
  }
render() {
    let posts = this.state.posts.map((post, index) => {
      return
      <View key={index}>
      <Text>Title: {post.title.rendered}</Text>
      </View>
    });
return (
      <View>
        <Text>List Of Posts</Text>
        <Text>{posts}</Text>
      </View>
     )
  }
}

This is the warning that I get:

Possible Unhandled Promise Rejection (id:0)
TypeError: Network request failed

How can I solve this?


Solution

  • I can only speak for Android: If you are running the emulator localhost (127.0.0.1) will refer to that 10.0.2.2 will refer to your actual localhost.

    So in that scenario you would use this: http://10.0.2.2:<port>/wordpress/wp-json/wp/v2/posts

    Hope this helps