Search code examples
jsonreact-nativepolling

React-Native: Parsing Simple JSON GET/POST and Refresh every X Seconds


Get data from JSON Response and populate a field and refresh every X Seconds. It doesn't have to be a background task, just while the screen is active.

The responses would be: res.name and res.host. It would also load the current image: res.imgurl

I have tried the code below, but the examples on the react site are quite complex and use lists, I just have simple JSON data, no array.

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

export default function App() {

  fetch("https://broadcast.truthnetwork.com/play-currentshow.lasso?station=WTRU")
    .then(res => res.json())
    .then(res => {
      console.log("Server response :- \n", res);
  })
    .catch(error => {
      console.log("Error from server :- \n", error);

  });

  return (
    <View style={styles.container}>
      <Text style={styles.sometext}>Show Name:</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { 
    flex: 1,
    backgroundColor: '#375963',
    alignItems: 'center',
    justifyContent: 'center',
  },
  sometext: {
    color: '#ffffff'
  }
});

Here is a sample JSON Response:

{
"name": "Encouraging Word", 
"imgurl": "https://broadcast.truthnetwork.com/_img/shows300/4B0FA4EA116331D9A1WH3AE062F0.jpg", 
"description": "This is a simple description", 
"slug": "encouraging-word-don-wilton", 
"weburl": "http://www.theencouragingword.org/", 
"feedurl": "http://feeds.feedburner.com/tewfbs", 
"host": "Don Wilton", 
"showid": "69"
}

I expect app to pull JSON and show the current show, show image and show host and refresh the data every 15-30 seconds (no background task is necessary, just while the screen is active).

Note: This API will work with GET OR POST on station=WTRU


Solution

  • The following approach might come in handy. The following example fetches data from an API every 5 seconds using JavaScript's setInterval. We are making the request once the component first renders, in the componentDidMount method and removing the interval once the component unmounts inside componentWillUnmount.

    You need to use state manipulation to update your screen after each api request after every x seconds. Since each state update causes a re-render.

    Sandbox Link: https://codesandbox.io/s/falling-pine-81hx4?fontsize=14

    Read more about setInterval here: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

    import React from "react";
    import ReactDOM from "react-dom";
    
    import "./styles.css";
    
    class App extends React.Component {
    
      state = {
        data: {}
      } 
    
      componentDidMount() {
        this.getData();
        this.interval = setInterval(() => {
          this.getData();
        }, 5000);
      }
    
      getData = () => {
        fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(response => response.json())
        .then(json => {
          console.log(json);
          this.setState({ data: json })
        })
      }
    
      componentWillUnmount() {
        clearInterval(this.interval);
      }
    
      render() {
        return (
          <div className="App">
            <p>{this.state.data.title}</p>
          </div>
        );
      }
    }