From c7fcf05857716e187c064d7ba21f27962015b71d Mon Sep 17 00:00:00 2001 From: Renard Date: Mon, 16 Sep 2019 13:32:35 -0300 Subject: Autorefresh para Thread --- src/Thread.js | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 56 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Thread.js b/src/Thread.js index 022e360..f23c081 100644 --- a/src/Thread.js +++ b/src/Thread.js @@ -19,8 +19,12 @@ class Thread extends Component { this.state = { isLoading: true, thread: [], - error: null + error: null, + autoRefresh: null }; + this.lastTime = 0; + this.refreshCooldown = 15; + this.cooldownCounter = 0; } componentDidMount() { @@ -39,10 +43,59 @@ class Thread extends Component { if (resource["state"] === "error") { this.setState({ error: resource }); } - this.setState({ isLoading: false, thread: resource }); + this.setState({ + isLoading: false, + thread: resource, + autoRefresh: setInterval(() => this.updateReplies(), 1000) + }); + this.lastTime = resource.time; }); - /* .catch(console.error); */ } + + componentWillUnmount() { + clearInterval(this.state.autoRefresh); + } + + async updateReplies() { + this.cooldownCounter++; + if (this.cooldownCounter < this.refreshCooldown) { + return; + } else { + this.cooldownCounter = 0; + } + + let apiURl = `https://bienvenidoainternet.org/cgi/api/thread?dir=${ + this.props.dir + }&${this.props.id > 1000000 ? "ts" : "id"}=${this.props.id}&offset=${ + this.state.thread.posts.length + }&time=${this.lastTime}`; + + fetch(apiURl) + .then(response => { + return response.json(); + }) + .then(resource => { + if (resource.state === "success") { + if (resource.posts.length > 0) { + const newPosts = this.state.thread.posts.concat(resource.posts); + this.setState(({ thread }) => ({ + thread: { + ...thread, + posts: newPosts + } + })); + this.refreshCooldown = 15; + } else { + this.refreshCooldown += 15; + if (this.refreshCooldown > 60) { + this.refreshCooldown = 60; + } + } + } + this.lastTime = resource.time; + }); + } + render() { const { isLoading, error } = this.state; -- cgit v1.2.1-18-gbd029