Skip to content

Instantly share code, notes, and snippets.

@quicksnap
Last active March 21, 2018 18:21
Show Gist options
  • Save quicksnap/d63088eda4622d5d1305bedcda9f9735 to your computer and use it in GitHub Desktop.
Save quicksnap/d63088eda4622d5d1305bedcda9f9735 to your computer and use it in GitHub Desktop.
import React from 'react';
import { KitAudioEntry } from '../../state/contentTypes';
import { Div } from 'glamorous';
type AudioProps = {
data: KitAudioEntry;
};
type State = {
iframeCode: string | null | undefined;
loading: boolean;
error: boolean;
};
class Audio extends React.Component<AudioProps, State> {
state = {
iframeCode: null,
loading: false,
error: false,
};
getUrl = (props = this.props) => this.props.data.fields.url;
_latestPromise: Promise<string> | null = null;
async fetchOembed() {
const userUrl = this.getUrl();
if (!userUrl) {
return;
}
this.setState({ loading: true, error: false });
this._latestPromise = new Promise<string>(async (resolve, reject) => {
try {
const result = await fetch(
`http://soundcloud.com/oembed?format=json&url=${userUrl}&iframe=true&maxheight=81`,
);
const json = await result.json();
resolve(json.html);
} catch (e) {
reject(e);
}
});
const awaited = this._latestPromise;
let html;
try {
html = await awaited;
} catch (e) {
this.setState({ error: true, loading: false });
}
// If a newer promise has been fired off while we were waiting for the resul tof this one, discard the result
// and exit immedately
if (this._latestPromise !== awaited) {
return;
}
this.setState({ iframeCode: html, loading: false });
}
componentDidMount() {
this.fetchOembed();
}
componentDidUpdate(prevProps: AudioProps) {
if (this.getUrl(prevProps) !== this.getUrl()) {
this.fetchOembed();
}
}
render() {
if (this.state.loading) {
return <Div>Loading SoundCloud...</Div>;
}
if (this.state.error) {
return <Div>There was an error loading SoundCloud.</Div>;
}
if (this.state.iframeCode) {
return (
<div dangerouslySetInnerHTML={{ __html: this.state.iframeCode! }} />
);
}
return <Div>SoundCloud Audio Unavailable</Div>;
}
}
export { Audio };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment