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

javascript - How to auto refresh data in real time, react? - Stack Overflow

programmeradmin2浏览0评论

making a basic spotify app using React for the first time. currenty the "Now playing" feature is using a button to display what is being played by the user. How can I change this mand so it does it in real time as apposed to a click of a button?

<button onClick={() => this.getNowPlaying()}>
   Check Now Playing
 </button>

Any help would be great :) Full code example is below

import React, { Component } from 'react';
import './App.css';
import Spotify from 'spotify-web-api-js';

const spotifyWebApi = new Spotify();

class App extends Component {
  constructor(){
    super();
    const params = this.getHashParams();
    this.state ={
      loggedIn: params.access_token ? true : false,
      nowPlaying: {
        name: 'Not Checked',
        image: ''
       }
     }
    if (params.access_token){
      spotifyWebApi.setAccessToken(params.access_token)
    }
  }
  getHashParams() {
    var hashParams = {};
    var e, r = /([^&;=]+)=?([^&;]*)/g,
        q = window.location.hash.substring(1);
    while ( e = r.exec(q)) {
       hashParams[e[1]] = decodeURIComponent(e[2]);
    }
    return hashParams;
  }

  getNowPlaying(){
    spotifyWebApi.getMyCurrentPlaybackState()
      .then((response) => {
        this.setState({
          nowPlaying: {
            name: response.item.name,
            image: response.item.album.images[1].url
          }
        })
      }
    )
  }

  render() {
    return (
    <div className="App">
      <a href='http://localhost:8888'>
      <button>Login But With Spotify </button>
      </a>
      <div> Now Playing: { this.state.nowPlaying.name} </div>
    <div>
    <img src={ this.state.nowPlaying.image} style={{ width: 100}}/>
    </div>
    <button onClick={() => this.getNowPlaying()}>
      Check Now Playing
    </button>
    </div>

making a basic spotify app using React for the first time. currenty the "Now playing" feature is using a button to display what is being played by the user. How can I change this mand so it does it in real time as apposed to a click of a button?

<button onClick={() => this.getNowPlaying()}>
   Check Now Playing
 </button>

Any help would be great :) Full code example is below

import React, { Component } from 'react';
import './App.css';
import Spotify from 'spotify-web-api-js';

const spotifyWebApi = new Spotify();

class App extends Component {
  constructor(){
    super();
    const params = this.getHashParams();
    this.state ={
      loggedIn: params.access_token ? true : false,
      nowPlaying: {
        name: 'Not Checked',
        image: ''
       }
     }
    if (params.access_token){
      spotifyWebApi.setAccessToken(params.access_token)
    }
  }
  getHashParams() {
    var hashParams = {};
    var e, r = /([^&;=]+)=?([^&;]*)/g,
        q = window.location.hash.substring(1);
    while ( e = r.exec(q)) {
       hashParams[e[1]] = decodeURIComponent(e[2]);
    }
    return hashParams;
  }

  getNowPlaying(){
    spotifyWebApi.getMyCurrentPlaybackState()
      .then((response) => {
        this.setState({
          nowPlaying: {
            name: response.item.name,
            image: response.item.album.images[1].url
          }
        })
      }
    )
  }

  render() {
    return (
    <div className="App">
      <a href='http://localhost:8888'>
      <button>Login But With Spotify </button>
      </a>
      <div> Now Playing: { this.state.nowPlaying.name} </div>
    <div>
    <img src={ this.state.nowPlaying.image} style={{ width: 100}}/>
    </div>
    <button onClick={() => this.getNowPlaying()}>
      Check Now Playing
    </button>
    </div>
Share Improve this question asked Mar 3, 2020 at 21:24 TheMayerofTheMayerof 1933 gold badges4 silver badges17 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 1

Not sure what you mean exactly by "real time", but you could set an interval to check using the api what song is playing.

Something like:

class App extends Component {
//your code ..

this.interval;

ponentDidMount() {
  this.interval = setInterval(this.getNowPlaying, 500); // <- time in ms
}

stopInterval() {
  clearInterval(this.interval);
}

ponentWillUnmount() {
  this.stopInterval();
}
}

You could add

ponentDidMount(){
   this.interval = setInterval(() => {
      // Spotify API for getting current 
      // setState if the song has changed
   }, 500);
}
ponentWillUnmount() {
    clearInterval(this.interval);
  }

I'm personally not a huge fan of this approach. But it's a start.

发布评论

评论列表(0)

  1. 暂无评论