Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  70] [ 7]  / answers: 1 / hits: 84748  / 6 Years ago, sat, february 3, 2018, 12:00:00

I've made a dashboard in React. It has no active updating, no buttons, fields or drop-downs. It will be deployed on a wall TV for viewing. All panels (9 total) are updated through the API call. The initial call (seen below) works, and all JSON data is fetched and the dashboard is initially updated.



BOTTOM LINE PROBLEM: I need to call the API every 30 sec to 1 minute after the initial call to check for updates.



I have attempted setInterval inside the componentDidMount() as suggested by people on here answering others' questions and I get an error await is a reserved word. I've read about forceUpdate() which seems logical for my use case given what the facebook/react page says about it. But, I've read on here as well to stay away from that...



The code below is a light version of the code I'm using. I've removed many of the components and imports for brevity's sake. Any help would be greatly appreciated.



import React, { Component } from 'react';

import Panelone from './Components/Panelone';
import Paneltwo from './Components/Paneltwo';

class App extends Component {

state = {
panelone: [],
paneltwo: []
}

async componentDidMount() {
try {
const res = await fetch('https://api.apijson.com/...');
const blocks = await res.json();
const dataPanelone = blocks.panelone;
const dataPaneltwo = blocks.paneltwo;

this.setState({
panelone: dataPanelone,
paneltwo: dataPaneltwo,
})
} catch(e) {
console.log(e);
}

render () {
return (
<div className=App>
<div className=wrapper>
<Panelone panelone={this.state} />
<Paneltwo paneltwo={this.state} />
</div>
</div>
);
}
}

export default App;

More From » reactjs

 Answers
7

In order to use await, the function directly enclosing it needs to be async. According to you if you want to use setInterval inside componentDidMount, adding async to the inner function will solve the issue. Here is the code,



 async componentDidMount() {
try {
setInterval(async () => {
const res = await fetch('https://api.apijson.com/...');
const blocks = await res.json();
const dataPanelone = blocks.panelone;
const dataPaneltwo = blocks.paneltwo;

this.setState({
panelone: dataPanelone,
paneltwo: dataPaneltwo,
})
}, 30000);
} catch(e) {
console.log(e);
}
}


Also instead of using setInterval globally, you should consider using react-timer-mixin. https://facebook.github.io/react-native/docs/timers.html#timermixin


[#55271] Thursday, February 1, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nolancampbellc

Total Points: 9
Total Questions: 102
Total Answers: 101

Location: Saint Vincent and the Grenadines
Member since Mon, Jan 16, 2023
1 Year ago
;