Last active
July 8, 2019 13:52
-
-
Save Bitaru/9e5243acba0ad45c6b81693bbbd1df75 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import { PropTypes } from 'prop-types'; | |
const randomKey = () => Math.random().toString(36).substring(7); | |
const waitForFindify = () => new Promise(resolve => { | |
if (window.findify) return resolve(window.findify); | |
(window.findifyCallbacks = window.findifyCallbacks || []).push((findify) => resolve(findify)); | |
}) | |
export class Findify extends Component{ | |
container = undefined; | |
findifyKey = undefined; | |
state = { | |
isLoaded: false, | |
} | |
static propTypes = { | |
widgetKey: PropTypes.string, | |
type: PropTypes.oneOf(['search', 'recommendation', 'autocomplete']), | |
options: PropTypes.object | |
} | |
componentWillUnmount() { | |
if (this.findifyKey) { | |
window.findify.widgets.detach(this.findifyKey); | |
} | |
} | |
handleFirstResponse = (items) => { | |
this.setState({ isLoaded: true }); | |
window.findify.widgets.get(this.findifyKey).agent.off(this.handleFirstResponse) | |
} | |
register = (container) => { | |
if (this.container || !container) return; | |
this.container = container; | |
this.renderFindify(container); | |
} | |
renderFindify = async (container) => { | |
const { widgetKey, type, options, config } = this.props; | |
this.findifyKey = widgetKey || randomKey(); | |
const findify = await waitForFindify(); | |
findify.widgets.attach(container, type, { ...config, widgetKey: this.findifyKey }); | |
findify | |
.widgets | |
.get(this.findifyKey) | |
.agent | |
.defaults(options) | |
.on('change:items', this.handleFirstResponse); | |
} | |
render() { | |
const { isLoaded } = this.state; | |
return ( | |
<> | |
{ !isLoaded && <div className='YOUR_LOADER' /> } | |
<div ref={this.register} /> | |
</> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment