最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to fetch data automatically every minute in React? - Stack Overflow

programmeradmin2浏览0评论

I want to fetch my data automatically every minute. The data i am fetching, are coordinates. I want to know the live location of a person and print the coordinates. Right now, i have this:

import React, { Component } from 'react';
 
class Test3 extends Component{
    state = {
        loading: true,
        coordinates: null,
    }

    async ponentDidMount(){
        const url = ":4000/gps_history?team_id=10";
        const response = await fetch(url);
        const data = await response.json();
        
        this.setState({coordinates: data, loading: false });
    }
    render(){
        const { loading, coordinates } = this.state
        return(
            <div>
                {loading || !coordinates ? (
                    <div>loading...</div>
                ) : (
                    <div>
                        {coordinates.map((coordinate, index) => {
                             return (
                               <div key={index}>
                                    <p>Longitute: {coordinate.lon}</p>
                                    <p>Latitude: {coordinate.lat}</p>
                                    <p>Time: {coordinate.timestamp}</p>
                                    <p>...............</p>
                               </div> 
                             )
                         })}
                    </div>
                )}
            </div>
        )
    }
}

export default Test3;

I want to fetch my data automatically every minute. The data i am fetching, are coordinates. I want to know the live location of a person and print the coordinates. Right now, i have this:

import React, { Component } from 'react';
 
class Test3 extends Component{
    state = {
        loading: true,
        coordinates: null,
    }

    async ponentDidMount(){
        const url = "https://ttr.vsbbn.nl:4000/gps_history?team_id=10";
        const response = await fetch(url);
        const data = await response.json();
        
        this.setState({coordinates: data, loading: false });
    }
    render(){
        const { loading, coordinates } = this.state
        return(
            <div>
                {loading || !coordinates ? (
                    <div>loading...</div>
                ) : (
                    <div>
                        {coordinates.map((coordinate, index) => {
                             return (
                               <div key={index}>
                                    <p>Longitute: {coordinate.lon}</p>
                                    <p>Latitude: {coordinate.lat}</p>
                                    <p>Time: {coordinate.timestamp}</p>
                                    <p>...............</p>
                               </div> 
                             )
                         })}
                    </div>
                )}
            </div>
        )
    }
}

export default Test3;

Is there any possibility to build this in the application?

Share Improve this question asked Jan 7, 2020 at 15:14 K.V.K.V. 511 silver badge6 bronze badges 3
  • 1 you can use setInterval function with a timeout of 1minute so every 1minute it will call – Beginner Commented Jan 7, 2020 at 15:17
  • Don't use async in front of any lifecycle methods, it will affect the performance of the lifecycle methods – Raghul SK Commented Jan 7, 2020 at 15:28
  • Does this answer your question? Update React ponent every second – Emile Bergeron Commented Jan 7, 2020 at 15:33
Add a ment  | 

3 Answers 3

Reset to default 3

A way to do this is using this approach:

import React, { Component } from 'react';

class Test3 extends Component{
    state = {
        loading: true,
        coordinates: null,
    }
    intervalId = null;

    fetchData = async () => {
     const url = "https://ttr.vsbbn.nl:4000/gps_history?team_id=10";
        const response = await fetch(url);
        const data = await response.json();

        this.setState({coordinates: data, loading: false });
    }

    async ponentDidMount(){
     await this.fetchData();

     this.intervalId = setInterval(() => {
        this.fetchData();
     }, 1000 * 60)
    }

    ponentWillUnmount() {
      clearInterval(this.intervalId)
    }

    render(){
        const { loading, coordinates } = this.state
        return(
            <div>
                {loading || !coordinates ? (
                    <div>loading...</div>
                ) : (
                    <div>
                        {coordinates.map((coordinate, index) => {
                             return (
                               <div key={index}>
                                    <p>Longitute: {coordinate.lon}</p>
                                    <p>Latitude: {coordinate.lat}</p>
                                    <p>Time: {coordinate.timestamp}</p>
                                    <p>...............</p>
                               </div> 
                             )
                         })}
                    </div>
                )}
            </div>
        )
    }
}

export default Test3;

The other answers work, but use Class-based ponents. This approach uses React Hooks.

Here's the example https://codesandbox.io/s/distracted-pond-g81ty

import React, { useState, useEffect, useRef } from "react";

// Dan's useInterval hook https://overreacted.io/making-setinterval-declarative-with-react-hooks/
function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

function Request() {
  let [requestCount, setRequestCount] = useState(0);

  // Run every second
  const delay = 1000;

  useInterval(() => {
    // Make the request here
    setRequestCount(requestCount + 1);
  }, delay);

  return <h1>{requestCount}</h1>;
}

You can use setInterval like this for specific time if you are having different values/data on api call.

    async ponentDidMount(){
       setInterval(()=>{
       const url = "https://ttr.vsbbn.nl:4000/gps_history?team_id=10";
        const response = await fetch(url);
        const data = await response.json();

        this.setState({coordinates: data, loading: false });
       },3000)
    }
发布评论

评论列表(0)

  1. 暂无评论