James Brett
James Brett

Reputation: 362

React-Native render json from fetch

I have a fetch returning on ComponentDidMount(). Trying to get the response to render on the page.

I have set the state as follows:

this.state = {
  loading: true,
  file: null,
  video: null,
  marks: []
};

and my fetch:

componentDidMount() {
return fetch('http://10.0.2.2:8080/marks/createMark')
  .then(response => response.json())
  .then((data) => {
    this.setState({
      loading: false,
      marks: data.mark
    }, () => {
      console.log(data.mark);
      console.log(this.state.marks);
      // const dataMap = data.mark.map((item) => {
      //   return {
      //     key: item.id,
      //     label: item.mark
      //   };
      // });
    });
  })
  .catch(err => console.log(err));

}

Now my render inside of the return:

 const { marks } = this.state;

      <FlatList
        data={marks}
        renderItem={({ item }) => <Text>{item.mark}</Text>}
        keyExtractor={(item, index) => index}
      />

Do I have to map the data then try to render it??

OUTPUT OF console.log(this.state.marks):

{ _id: '5b61e47a55a0000aa980fab1', mark: 'ItHe', __v: 0 }

The mark is a pseudorandom string that can contain letters and numbers created on the backend

Upvotes: 0

Views: 985

Answers (2)

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

As this.state.marks is an object. First, you need to convert it to this form [{}]. You can do the following changes to make it work.

fetch('http://10.0.2.2:8080/marks/createMark')
.then(response => response.json())
.then((data) => {

  let marks = [data.mark];  //Add this line

  this.setState({
    loading: false,
    marks: marks    // Change this line
  }, () => {  
       ....
 Rest of your code

Upvotes: 1

chandlervdw
chandlervdw

Reputation: 3226

marks is an array but you're not sharing what each object in the array looks like. If it's an array of strings, you're good but if it's an object, you'll need to destructure it and pull out the string you're looking to render.

<Text>{item.mark.someKeyWhoseValueIsAString}</Text

Upvotes: 0

Related Questions