0

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

2
  • Can u please share the output of console.log((this.state.marks). Commented Aug 1, 2018 at 16:43
  • ok I added the console.log() output Commented Aug 1, 2018 at 16:51

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Mohammed. I really appreciate your help. This is the correct answer but I cannot up-vote because of my low reputation.
It's my pleasure. :-)
0

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

Comments

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.