Miles Works
Miles Works

Reputation: 639

Pulling Data from JSON with React-Native

What's wrong with this picture ? :-)

I'm trying to pull values from my wordpress JSON objects.

I must not be addressing them the correct/proper way with React-Native.

Can someone direct me as to how to form the correct console log statement ?

As it stands right now, the variable 'theMediaLink' is coming up 'undefined' in the console log. :-(

  state={
    data:[]
  }

  fetchData = async() => {
    const response = await
    //response
    fetch('http://example.com/wp-json/wp/v2/posts/')
    //posts
    const posts = await response.json();
    this.setState({data:posts});

    const theMediaLink = `https://example.com/wp-json/wp/v2/media/` + `${this.state.data.featuredmedia}`;
    console.log('theMediaLink_value: ', theMediaLink);
  }

I should add that the fetch is retrieving data as I use it later on with a FLATLIST to pull the posts. My question is I must be misforming the call, but how ?

Upvotes: 0

Views: 74

Answers (1)

bumbaneitr11
bumbaneitr11

Reputation: 101

This is more an issue of understanding of React rather than React Native.

Try this:

fetchData = async () => {
  const URL = 'http://example.com/wp-json/wp/v2/posts/'

  const response = await fetch(URL)

  const posts = await response.json();

  return this.setState({ data : posts }, () => {
    const { data } = this.state

    const theMediaLink = `https://example.com/wp-json/wp/v2/media/${ data.featuredmedia }`;

    console.log('theMediaLink_value: ', theMediaLink);
  });
}

Since setState is asynchronous, you won't be able to see the state update right away, that's why the callback is for.

More info on how to setState asynchronously and use its value after right here

Upvotes: 1

Related Questions