javascript - How to fetch repeatedly and render updated api data in reactjs? - Stack Overflow

I am trying to render time data from API endpoint The "currentFileTime" property is constant

I am trying to render time data from API endpoint The "currentFileTime" property is constantly changing but renders once on load. I tried setInterval method to update state but it doesn't work. May be I am making some mistake?

This is App.js:

import React , { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { data: []};
  }

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

  async fetchData() {
    try { 
          const response = await  fetch('');
          if (!response.ok) {throw Error(response.statusText);}
          const json = await response.json();
          this.setState({ data: json});
          console.log(json);
        }   
    catch (error) {console.log(error);}
  }

  render() {return (<div><h1>worldclockapi data (edit App.js)</h1>
                         <li>currentFileTime: {this.state.data.currentFileTime }</li>
              </div> );
            }
}

export default App;

How to render and update currentFileTime continuously in react ponent?

I am trying to render time data from API endpoint http://worldclockapi./api/json/utc/now The "currentFileTime" property is constantly changing but renders once on load. I tried setInterval method to update state but it doesn't work. May be I am making some mistake?

This is App.js:

import React , { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { data: []};
  }

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

  async fetchData() {
    try { 
          const response = await  fetch('http://worldclockapi./api/json/utc/now');
          if (!response.ok) {throw Error(response.statusText);}
          const json = await response.json();
          this.setState({ data: json});
          console.log(json);
        }   
    catch (error) {console.log(error);}
  }

  render() {return (<div><h1>worldclockapi. data (edit App.js)</h1>
                         <li>currentFileTime: {this.state.data.currentFileTime }</li>
              </div> );
            }
}

export default App;

How to render and update currentFileTime continuously in react ponent?

Share Improve this question edited Nov 24, 2019 at 16:21 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Nov 24, 2019 at 7:48 RobinRobin 151 silver badge5 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

the problem is ponentDidMount executed only once, after ponent mounted for the first time, for example if your state changes ponentDidMount is not gonna execute again. in your case i think it's better to use websockets but if u wanna keep useing this api u can use useEffect hook like below:

const [temp, setTemp] = useState(0)

useEffect(()=>{
  setIterval(()=>{
    setTemp((prevTemp)=>prevTemp+1)
  }, 2000)
}, [])

useEffect(()=>{
  fetchData()
}, [temp])

in the above code we have a temp variable and it's value update every 2 second and every time it gets updated the second useEffect run and the data will fetch and as a result the state's gonna change and element gets updated.

This is using the new hooks. This should solve the problems

import React, {useEffect, useState} from 'react';

import logo from './logo.svg';
import './App.css';

const App  = () => {
const [state, setState] = useState({data: []});

useEffect(()=>{
    fetchData();
}, [state]);

const fetchData =  async () => {
    try {
        const response = await  fetch('http://worldclockapi./api/json/utc/now');
        if (!response.ok) {throw Error(response.statusText);}
        const json = await response.json();
        setState({ data: json});
        console.log(json);
    }
    catch (error) {console.log(error);}
}

return (<div><h1>worldclockapi. data (edit App.js)</h1>
<li>currentFileTime: {state.data.currentFileTime }</li>
</div> );
}

export default App;

Try Calling fecthData recursively upon successful data retrieval like below. And you don't need to put "async" in front of ponentDidMount cause you ain't awaiting anything in the method call.

  async fetchData() {
    try { 
          const response = await  fetch('http://worldclockapi./api/json/utc/now');
          if (!response.ok) {throw Error(response.statusText);}
          const json = await response.json();
          this.setState({ data: json});
          console.log(json);

          // set the time below to how frequently you wanna update 
          setTimeout(() => this.fetchData(), 5000);
          //
        }   
    catch (error) {console.log(error);}
  }

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

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

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

关注微信