Home React Native REST API will not convert JSON object to String without displaying [object Object]
Reply: 3

React Native REST API will not convert JSON object to String without displaying [object Object]

joe the coder
1#
joe the coder Published in 2018-01-12 23:18:27Z

The problem is that the React Native App display will not display the contents of the JSON string stored in getMovies(). The display logic in getMovies() does not recognize a Text to print out, and only displays [object Object] with out any contents.

import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View } from 'react-native';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component<{}> {

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>

        <Text>{getMovies().toString()}</Text>


      </View>


    );
  }
}

function getMovies() {
    var movies = getMoviesFromApiAsync();

    return movies;
}

function getMoviesFromApiAsync() {
    return fetch('https://facebook.github.io/react-native/movies.json')
        .then((response) => response.json())
        .then((responseJson) => {
            return responseJson.movies;
        })
        .catch((error) => {
            console.error(error);
        });
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
casieber
2#
casieber Reply to 2018-01-13 00:01:31Z

Without a custom toString() implementation, calling toString() on an object will follow the prototype chain up to the Object prototype toString method, which simply prints out [object Object] like you are seeing.

You can either:

  1. Replace getMovies().toString() with JSON.stringify(getMovies()), which will get you closer to what you want, but it will have curly braces included in the string.
  2. Replace getMovies().toString() with a custom renderer like Object.values(getMovies()).map(movie => <MovieDetails movie={movie} />) where you have built your own MovieDetails component.
balti bahaeddine
3#
balti bahaeddine Reply to 2018-01-13 10:29:29Z

You can view this here https://repl.it/repls/RashBowedHarpyeagle

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
export default class App extends Component<{}> {
   constructor(props){
     super(props)
     this.state = {
      movies: []
     }
   }
  componentDidMount(){
    this.getMovies()
  }  
  getMovies = () => {
    this.getMoviesFromApiAsync()
    .then(movies => {
      console.log(movies)
      this.setState({
        movies
      })
    })
 }
  getMoviesFromApiAsync = () => {
    return fetch('https://facebook.github.io/react-native/movies.json')
        .then(response=> response.json())
        .then(responseJson => responseJson.movies)
        .catch(error => console.error(error));
 }
  render() {
    return (
      <View style={styles.container}>
        {
          this.state.movies.map((movie, index) => {
           return <Text key = {index}>{movie.title}<Text>{movie.releaseYear}</Text></Text>    
          })
        }
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});
Cesar Contreras
4#
Cesar Contreras Reply to 2018-01-13 00:06:09Z

The problem with that is that the function getMovies() return a promise and its value it's not resolved until is being execute and then call the then() function. This is the solution:

export default class App extends Component {

  state = {
    movies: [],
  }

  componentDidMount() {
    getMovies().then(movies => this.setState({ movies: movies.map(movie => movie.title).join(', ') }));
  }

  render() {
    const { movies } = this.state;
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>

        <Text>{movies}</Text>


      </View>


    );
  }
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.356628 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO