Skip to content

Instantly share code, notes, and snippets.

@jermsam
Created April 21, 2019 16:41
Show Gist options
  • Save jermsam/f53f40437550cd91bb5359c5d75f0e7a to your computer and use it in GitHub Desktop.
Save jermsam/f53f40437550cd91bb5359c5d75f0e7a to your computer and use it in GitHub Desktop.
import _ from 'lodash';
/* eslint-disable no-console */
import React, { Component } from 'react';
import { Form, Search } from 'semantic-ui-react';
import YTSearch from 'youtube-api-search';
import moment from 'moment';
// import { app } from '../../feathers';
const { API_KEY } = process.env;
const INITIAL_STATE = {
videos: [],
search: true,
videoTitle: ''
};
export default class VideoTitleSearch extends Component {
state = INITIAL_STATE;
_isMounted = false;
componentWillMount() {
this.resetComponent();
}
componentDidMount() {
this._isMounted = true;
}
componentWillUnmount() {
this._isMounted = false;
}
resetComponent = () => {
if (this._isMounted) {
this.setState({ isLoading: false, videos: [], videoTitle: '' });
}
};
handleResultSelect = (e, { result: { id, title } }) => {
const video = `https://www.youtube.com/watch?v=${id}`;
this.setState({ isLoading: false, videoTitle: title });
const { setvideo } = this.props;
setvideo(video);
};
handleSearchChange = async (e, { value }) => {
if (this._isMounted) {
this.setState({ isLoading: true, videoTitle: value });
YTSearch({ key: API_KEY, value }, data => {
try {
if (data) {
// console.log(data);
const source = data.map(
({
id: { videoId },
etag,
snippet: {
channelTitle,
description,
publishedAt,
thumbnails: {
default: { url }
}
}
}) => {
if (etag) {
return {
id: videoId,
title: channelTitle,
image: url,
description,
price: `(${moment(publishedAt).format('MM/DD/YYYY')})`
};
}
return {
id: null,
title: ``,
image: ``,
description: ``,
price: ``
};
}
);
const { videoTitle } = this.state;
// console.log('source, ', source);
if (videoTitle.length < 1) return this.resetComponent();
const re = new RegExp(_.escapeRegExp(videoTitle), 'i');
const isMatch = result => re.test(result && result.title);
if (this._isMounted) {
this.setState({
isLoading: false,
videos: _.filter(source, isMatch)
});
}
}
// this.setState({ videos: data, videoTitle: data[0] });
// console.log(this.state.videos);
} catch (err) {
console.log('Error: ', err);
}
return null;
});
}
};
render() {
const { isLoading, videoTitle, videos } = this.state;
// const { open, onClose } = this.props;
return (
<Form>
<Search
fluid
placeholder="Search for your Youtube video by name"
loading={isLoading}
onResultSelect={this.handleResultSelect}
onSearchChange={_.debounce(this.handleSearchChange, 500, {
leading: true
})}
results={videos}
value={videoTitle}
{...this.props}
size="large"
/>
</Form>
);
}
}
VideoTitleSearch.getInitialProps = ({ setvideo }) => ({
setvideo
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment