HTTP React Native Request

Asked

Viewed 2,549 times

4

an API sends a status:false the code taken status. While status==false, will be rendered the image of exclamation.png and message 'Pedido em Análise'. Case status change to true both image and message values change(check.png and 'Pedido Aprovado!'). Unfortunately I can’t, as I do to check if the status moved to true?

Code at the Expo >> https://snack.expo.io/@domxicote/test

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,
  },
});

  • You can create a function that will run in time periods like the javascript setInterval. Using IdidMount you will only be able to perform this function of yours only 1 time and you will not be able to see if the status has changed.

  • You can implement something using Socket.io as well, take a look at: https://github.com/vinnyoodles/react-native-socketio-example

1 answer

4


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);
  });
}

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.