Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching JSON and iterating through the values in react-native

I'm new to react native, and I'm trying to simply iterate through a sample json file but am receiving the error undefined is not a function (evaluating 'this.state.results.map')

I have set the state initially to be an object, so not sure why i am receiving this error.

Here is the JS:

import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';

var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';

class WPReact extends Component {
  constructor(props) {
    super(props);
    this.state = {results: []};
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results : { responseData }
        });
      })
      .done();
  }
  render() {
    return this.renderJSON();
  }
  renderJSON() {
    contents = this.state.results.map((item) => {
      <View key={item.movies.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.movies.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
}

var Dimensions = require('Dimensions');

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => WPReact);

EDIT

So i have edited the renderJSON() to and also removed the braces of responseData as you said, as it was already an object:

renderJSON() {

    console.log(this.state.results.description);
    contents = this.state.results.movies.map((item) => {
      <View key={item.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }

I added a console log to see if i can output some of the data, and i can see the description. The sample JSON i am using is (demo from react):

{
  "title": "The Basics - Networking",
  "description": "Your app fetched this from a remote endpoint!",
  "movies": [
    { "title": "Star Wars", "releaseYear": "1977"},
    { "title": "Back to the Future", "releaseYear": "1985"},
    { "title": "The Matrix", "releaseYear": "1999"},
    { "title": "Inception", "releaseYear": "2010"},
    { "title": "Interstellar", "releaseYear": "2014"}
  ]
}

I can log the description and title. But I am still receiving: ReactNativeJS: undefined is not an object (evaluating 'this.state.results.movies.map')

And if I try logging console.log(this.state.results.movies[0].title) I am receiving undefined is not an object (evaluating 'this.state.results.movies[0]')

fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        console.log(responseData);
        this.setState({
          results : responseData
        });
      })
      .done();
  }

console.log(responseData) shows:

03-29 13:49:53.028  3062  4143 I ReactNativeJS: { title: 'The Basics - Networking',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   description: 'Your app fetched this from a remote endpoint!',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   movies: 
03-29 13:49:53.028  3062  4143 I ReactNativeJS:    [ { title: 'Star Wars', releaseYear: '1977' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Back to the Future', releaseYear: '1985' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'The Matrix', releaseYear: '1999' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Inception', releaseYear: '2010' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Interstellar', releaseYear: '2014' } ] }

console.log(this.state.results.movies);

03-29 14:18:05.483  3062  4726 I ReactNativeJS: undefined
03-29 14:18:05.510  3062  4726 I ReactNativeJS: [ { title: 'Star Wars', releaseYear: '1977' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Back to the Future', releaseYear: '1985' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'The Matrix', releaseYear: '1999' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Inception', releaseYear: '2010' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Interstellar', releaseYear: '2014' } ]
like image 966
KT.C Avatar asked Mar 29 '17 11:03

KT.C


1 Answers

I see a couple of things you need to change.

Firstly, you need to bind fetchData method when you are using ES6 doing this this.fetchData = this.fetchData.bind(this); in the constructor (look for other ways to do this).

Secondly, map should be applied to this.state.results.movies due this is the array (following your post). this.state.results is not an array, is an object containing an array.

import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';

var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';

class WPReact extends Component {
  constructor(props) {
    super(props);

    this.state = {
      //Lets initialize results with the same struct we expect to receive from the api
      results: {
        title: '',
        description: '',
        movies: []
      }
    };
    //Using ES6 we need to bind methods to access 'this'
    this.fetchData = this.fetchData.bind(this);
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results: responseData
        });
      })
      .done();
  }

  render() {
    //this.state.results.movies is the array you have to iterate
    contents = this.state.results.movies.map((item) => {
      //We need to return the corresponding mapping for each item too.
      return (
          <View key={item.title} style={ styles.container }>
            <Text style={styles.title}>
              {item.title}
            </Text>
          </View>
        );
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
}

var Dimensions = require('Dimensions');

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => WPReact);

Let me know if its works, I havent tested yet but I will soon.

like image 120
Facundo La Rocca Avatar answered Nov 14 '22 20:11

Facundo La Rocca