3

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 componentDidMount(){
        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?

3
  • 1
    you can use setInterval function with a timeout of 1minute so every 1minute it will call 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 Commented Jan 7, 2020 at 15:28
  • Does this answer your question? Update React component every second Commented Jan 7, 2020 at 15:33

3 Answers 3

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 componentDidMount(){
     await this.fetchData();

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

    componentWillUnmount() {
      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;
Sign up to request clarification or add additional context in comments.

1 Comment

Please, don't use an interactive snippet if the code isn't runnable.
3

The other answers work, but use Class-based components. 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>;
}

Comments

1

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

    async componentDidMount(){
       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)
    }

1 Comment

The async keyword is not used on the right function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.