javascript - React fetching data from api, and display as list in real-time - Stack Overflow

I want to fetch data from my local api, and display with real-time updating.The fetch and display as l

I want to fetch data from my local api, and display with real-time updating. The fetch and display as list from object, i have, and it works fine, but the list is not updating when new data is available on the api.

Can someon explain to me what is needed in my example, to make real-time updating of data fetching and display?

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

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: [],
    }
  }

  ponentDidMount() {
    var params = {
      method: 'GET',
      headers: {
        "cache-control": 'no-cache',
        pragma: 'no-cache',
      }
    };

    return fetch('http://192.168.1.54:8000/api/measurement', params)
    .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        });
      })
      .catch((error) => {
        console.log(error);
      }
    );
  }

  render() {
    if(this.state.isLoading) {
      return (
        <View style={styles.container}>
          <ActivityIndicator />
        </View>
      )
    } else {
      let measurements = this.state.dataSource.map((val, key) => {
        return  <View key={key} style={styles.item}>
                  <Text>{val.hardwareUnit} - {val.measurementType} : {val.value}</Text>
                </View>
      });

      return (
        <View style={styles.container}>
          <Text style={styles.title}>Measurements</Text>
          {/* Display the latest 5 measurements from API */}
          {measurements.slice(Math.max(measurements.length - 5, 0))}
        </View>
      )
    }
  }
}

I want to fetch data from my local api, and display with real-time updating. The fetch and display as list from object, i have, and it works fine, but the list is not updating when new data is available on the api.

Can someon explain to me what is needed in my example, to make real-time updating of data fetching and display?

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

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: [],
    }
  }

  ponentDidMount() {
    var params = {
      method: 'GET',
      headers: {
        "cache-control": 'no-cache',
        pragma: 'no-cache',
      }
    };

    return fetch('http://192.168.1.54:8000/api/measurement', params)
    .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        });
      })
      .catch((error) => {
        console.log(error);
      }
    );
  }

  render() {
    if(this.state.isLoading) {
      return (
        <View style={styles.container}>
          <ActivityIndicator />
        </View>
      )
    } else {
      let measurements = this.state.dataSource.map((val, key) => {
        return  <View key={key} style={styles.item}>
                  <Text>{val.hardwareUnit} - {val.measurementType} : {val.value}</Text>
                </View>
      });

      return (
        <View style={styles.container}>
          <Text style={styles.title}>Measurements</Text>
          {/* Display the latest 5 measurements from API */}
          {measurements.slice(Math.max(measurements.length - 5, 0))}
        </View>
      )
    }
  }
}
Share Improve this question asked Feb 16, 2023 at 10:23 XmlSharkXmlShark 1148 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

You need to implement sockets. Trigger an event from backend when changes are made and listen for those changes on frontend. On receiving event make the required changes on frontend

In order to render new data, you need to first have it. For this you will need the ponent to ask the data source. If it is a backend server, you can consider polling it, if the data you need does not need to be very accurate and can your app can handle some delays. But this will place some strain on the servers. But you can continue to use the stateless approach on the server and get away with it so as long as the polling request has the right ids.

Here one can set an Interval, poll the server to fetch data and rehydrate the state easily.

Alternatively you can set up a web socket connection. However this may need to maintain some state on the server depending on your use case.

Ref: https://blog.logrocket./websocket-tutorial-real-time-node-react/

Alternatively you can use Server Sent Events (again described in the article above.). But this I have felt to be a bigger challenge than web sockets for most cases. If you do not need to send any updates to the server, this could work as well.

Ref: https://developer.mozilla/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

what you need its called: websockets

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744754356a4591789.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信