export default () => ({ search: false, searchValue: '', isLoading: true, results: '', init() { // this.$el.classList.remove('hidden'); // this.openMenu(); // this.open(); }, closeSearch() { this.searchValue = ''; }, isSearchOpen() { return this.search === true; }, isMenuOpen() { return this.menu === true; }, showOverlay() { return this.search || this.menu }, shouldSearch() { return this.searchValue.length >= 2; }, searching(fetch = true) { if(fetch){ this.isLoading = true; this.$refs.results.classList.add('opacity-0') } else { this.isLoading = false; this.$refs.results.classList.remove('opacity-0') } }, fetchResults(query) { // console.log(query); if (this.shouldSearch) { this.searching(); fetch('/api/search', { method: 'POST', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: JSON.stringify({query: this.searchValue}) }).then(res => { if (res.ok) { return res.json(); } throw new Error('Something went wrong'); }).then(data => { this.results = data.html.length ? data.html : `No Result Found` setTimeout(this.searching(false), 2000) }) .catch( (error) => { console.log(error); }); } } });