HTTP Request React Native

4

An API sends a status:false the code gets status . While status==false , the image of exclamation.png and message 'Pedido em Análise' will be rendered. If status changes to true both image values and message changes ( check.png and 'Pedido Aprovado!' ). Unfortunately I can not, how do I check if status has changed to true ?

Code at Expo > > link

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

export default class Exemplo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      image: require('./src/exclamation.png'),
      message: 'Pedido em Análise',
    };
  }

  componentDidMount() {
    return fetch('https://recivida-dados.codeanyapp.com/response.json')
      .then(response => response.json())
      .then(responseJson => {
        if (responseJson.status) {
          this.setState({
            image: require('./src/check.png'),
            message: 'Pedido Aprovado!',
          });
        }
      })
      .catch(error => {
        console.error(error);
      });
  }

  render() {
    return (
      <View style={styles.container}>
        <Image style={styles.image} source={this.state.image} />
        <Text>
          {this.state.message}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  image: {
    width: 50,
    height: 50,
  },
});
    
asked by anonymous 07.05.2018 / 02:29

1 answer

3

You can use more or less like this

componentDidMount() {
    setInterval(() => this.GetStatus(), 10000);
}

function GetStatus(){
  fetch('https://recivida-dados.codeanyapp.com/response.json')
  .then(response => response.json())
  .then(responseJson => {
    if (responseJson.status) {
      this.setState({
        image: require('./src/check.png'),
        message: 'Pedido Aprovado!',
      });
    }
    else{
      //Do Something
    }
  })
  .catch(error => {
    console.error(error);
  });
}

In this way your function will run every 10 seconds and you can see if the status is still false or changed to true

    
10.05.2018 / 16:36