0

I'm currently using my api to render all posts in JSON to react native. But I keep getting this undefined error. And sometimes the data just wont render. Can anyone give me any help on rendering this data in react native? And explain to me what i'm doing wrong? I'm pretty new with JSON. Thanks :)

Here is my JSON:

{"data":[{"id":"1","type":"posts","links":{"self":"https://example.com/posts/1"},"attributes":{"title":"Laughter Post","context":{}},"relationships":{"user":{"links":{"self":"https://example.com/posts/1/relationships/user","related":"https://example.com/posts/1/user"}}}}]}

And here is my react native code:

import React, { Component } from "react";
import { FlatList, StyleSheet, Text, View } from "react-native";

export default class App extends Component {
state = {
data: []
};

componentWillMount() {
this.fetchData();
}

fetchData = async () => {
const response = await fetch("https://example.com/posts.json");
const json = await response.json();
this.setState({ data: json.data });
};

render() {
  return (
    <View style={styles.container}>
     <FlatList
      data={this.state.data}
      keyExtractor={item => item.toString()}
      renderItem={({ item }) =>
        <Text>
          {`${item.title}`}
        </Text>}
       />
    </View>
   );
  }
 }

 const styles = StyleSheet.create({
 container: {
 marginTop: 15,
 flex: 1,
 justifyContent: "center",
 alignItems: "center",
 backgroundColor: "#F5FCFF"
 }
 });

1 Answer 1

1

It seems you are accessing title directly from the root, but it is inside key attributes

It should be

{`${item. attributes.title}`}

Or else if you can tell us the exact error, we can help you more regarding this issue.

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

1 Comment

Wow I spent most of my day trying to figure this out. I feel quite stupid. It Worked! thank you so much!

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.