0

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 ?

4
  • when using await i don't think you need to do response.json() Commented Sep 26, 2018 at 17:17
  • Another thing, setState is asynchronous. but you can use it's callback argument to run code just after the state has been updated: setState({key:value}, () => {...}) Commented Sep 26, 2018 at 17:19
  • please check the value of this.state.data.featuredmedia. Do console.log( this.state.data.featuredmedia) I think it is undefined. Commented Sep 26, 2018 at 17:22
  • it is undefined. :-( Commented Sep 26, 2018 at 17:36

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Gotcha. Ok. I had bypassed that little detail about state that it's async. Ooops. Well that cleans up my code very nicely. It wasn't that awful but it's a lot more straight forward in this form. The only reason I'm trying to set those constants above is because I can't seem to form the proper call to get the json object > 'wp:featuredmedia', where the : is causing havoc with the call. RN throws a fit every time I do. As shown here > stackoverflow.com/questions/52519548/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.