W. Robarts
W. Robarts

Reputation: 151

React-native: how to get JSON from backend and put the objects in react-native elements, such as Text?

I am trying to fetch JSON data from a php file, which seems to work fine; I can alert values from the JSON. But I want to be able to put these values on the mobile app screen in Text elements or whatever. And I want this to happen when the screen opens, not when a button is pressed. So I made a function that fetches the JSON and I'm trying to return a value in Text elements. This function is called from the rendering. I don't get error messages, but it isn't working. Nothing shows up.

Here is the code:

import React, { Component } from 'react';
import { View, Text, AsyncStorage, Alert } from 'react-native';
import { UsersMap } from '../UsersMap';
import { PrimaryButton } from '../Buttons';
import styles from './styles';

class RestOptions extends Component {

    getSearchResults() {
        fetch('http://192.168.1.3/Restaurant_App/php/search_results.php')
        .then((response) => response.json())
        .then((responseJson) => {
            var JSON_Test = responseJson["distance"][0];
            //Alert.alert(JSON_Test);
            return (
                <View>
                    <Text>{JSON_Test}</Text>
                </View>
            );
        }).catch((error) => {
            console.error(error);
        });
    }

    setReservation = () => {
        this.props.navigation.navigate('SetReservation');
    };

    render() {
        return (
            <View>
                <UsersMap />
                {this.getSearchResults()}
                <PrimaryButton
                    label="Set Reservation"
                    onPress={() => this.setReservation()}
                />
            </View>
        );
    }
};

export default RestOptions;

This is what happens. The JSON value should appear between the map and the button:

Search Results Screen

Upvotes: 0

Views: 235

Answers (1)

NULL SWEΔT
NULL SWEΔT

Reputation: 2037

First of all, in order to fetch the data as the screen opens, you should use the lifecycle method componentWillMount, which executes before the first render, and then store the result in the component's state. React docs on state and lifecycle

class RestOptions extends Component {
    constructor(props) {
        super(props);
        this.state = {
            jsonTest: null
        }
    }

    componentWillMount() {
        this.getSearchResults();
    }

    getSearchResults() {
        fetch('http://192.168.1.3/Restaurant_App/php/search_results.php')
        .then((response) => response.json())
        .then((responseJson) => {
            var JSON_Test = responseJson["distance"][0];
            //Alert.alert(JSON_Test);
            this.setState({ jsonTest: JSON_Test });
        }).catch((error) => {
            console.error(error);
        });
    }
//...

Then you can display the value on the render() method:

render() {
    return (
        <View>
            <UsersMap />

            <Text>{this.state.jsonTest}</Text>

            <PrimaryButton
                label="Set Reservation"
                onPress={() => this.setReservation()}
            />
        </View>
    );
}

If the response is an array of values, you can use map() to display each of them in their own Text element:

{this.state.jsonTest.map((value, index) => <Text key={index}>{value}</Text>)}

Upvotes: 1

Related Questions