0

The following code is for a single post, axios fetches the current post ID and stores the result in post array. Keep in mind, only ONE post is stored since this is fetching a single post. The ID and date display properly but if I try to display nested items like rendered content it doesn't work.

Here is what the API json result looks like: enter image description here

    constructor(props) {
    super(props);

    this.state = {
      post: []
    };
  }

getPost() {
    axios
      .get('single_post_api')
      .then(response => {
        this.setState({
          post: response.data
        });
      });
}

componentDidMount() {    
    this.getPost();
  }

render() {
const data = this.state.post;

  return ( 
  <View>    
          <Text>{data.date}</Text>
          <Text>{data.slug}</Text>

///Neither of these work///
          <Text>{data.content.rendered}</Text>
          <Text>{data.content[0]}</Text>
////////////////////////////

  </View>
  );
}
3
  • You cannot just html as a value in react. Commented Sep 15, 2019 at 16:52
  • @HMR I'm not sure what you mean by this? Commented Sep 15, 2019 at 16:59
  • In the data content.rendered is html, you cannot do <div>{content.rendered}</div> but have to do it the way I mentioned earlier (because of xss attack). You could try <pre>{JSON.sringify(data,undefined,2)}</pre> and see where you are doing something wrong. Commented Sep 15, 2019 at 17:05

1 Answer 1

2

Try this.

render() {
  // If we run into a null, just render it as if we had an empty array.
  const posts = (this.state ?? this.state.posts) ? this.state.posts : [];

  return ( 
    <View>
      (posts.map((post, index) => (
        <View key={index}>
          <Text>{post.date}</Text>
          <Text>{post.slug}</Text>
          <Text>{post.content ? post.content.rendered : ""}</Text>
        </View>
      ));
  </View>
  );
}
Sign up to request clarification or add additional context in comments.

6 Comments

const data = this.state.post; was a spelling mistake for this question, I have fixed it in the question. I added [response.data] but I still can't display the nested items.
Gotcha. I've modified my original answer.
This code works, just curious why I can't just put {post.content.rendered} , why do I need this before it: {post.content ? post.content.rendered : ""}
You could probably do {post.content.rendered} and be just fine. However, if post.content were ever null, it would throw an exception.
I get "Undefined is not an object" error if I do it that way, even though it's the exact same post and it displays properly with {post.content ? post.content.rendered : ""}
|

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.