diff --git a/src/components/data/apps.json b/src/components/data/apps.json index d0c3fdc..903c79f 100644 --- a/src/components/data/apps.json +++ b/src/components/data/apps.json @@ -1,7 +1,7 @@ { "apps": [ { - "name": "my pi hole", + "name": "Pihole", "displayURL": "example.com", "URL": "https://example.com", "icon": "vpn_lock" diff --git a/src/components/searchBar.js b/src/components/searchBar.js index 3db9561..f7f1d11 100644 --- a/src/components/searchBar.js +++ b/src/components/searchBar.js @@ -1,7 +1,7 @@ -import React, { useState } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import styled from 'styled-components'; -import searchData from './data/search.json'; +import { ErrorMessage } from './elements'; import selectedTheme from './themeManager'; @@ -15,29 +15,40 @@ const SearchInput = styled.input` color: ${selectedTheme.mainColor}; `; -const handleQueryWithProvider = query => { - let queryArray = query.split(' '); - - let prefix = queryArray[0]; - - queryArray.shift(); - - let searchQuery = queryArray.join(' '); - - var foundProvider = false; - searchData.providers.forEach(provider => { - if (provider.prefix === prefix) { - foundProvider = true; - window.location = provider.url + searchQuery; - } - }); - - if (!foundProvider) { - window.location = 'https://google.com/search?q=' + query; +const handleResponse = response => { + if (response.ok) { + return response.json(); } + throw new Error('Failed to load app data.'); +}; + +const useSearchProviders = () => { + const [searchProviders, setSearchProviders] = useState({ + providers: [], + error: false + }); + const fetchSearchProviders = useCallback(() => { + (process.env.NODE_ENV === 'production' + ? fetch('/search.json').then(handleResponse) + : import('./data/search.json') + ) + .then(jsonResponse => { + setSearchProviders({ ...jsonResponse, error: false }); + }) + .catch(error => { + setSearchProviders({ providers: [], error: error.message }); + }); + }, []); + + useEffect(() => { + fetchSearchProviders(); + }, [fetchSearchProviders]); + return searchProviders; }; const SearchBar = () => { + const searchProviders = useSearchProviders(); + let [input, setInput] = useState(); const handleSearchQuery = e => { @@ -52,8 +63,31 @@ const SearchBar = () => { e.preventDefault(); }; + const handleQueryWithProvider = query => { + let queryArray = query.split(' '); + let prefix = queryArray[0]; + queryArray.shift(); + + let searchQuery = queryArray.join(' '); + + var foundProvider = false; + searchProviders.providers.forEach(provider => { + if (provider.prefix === prefix) { + foundProvider = true; + window.location = provider.url + searchQuery; + } + }); + + if (!foundProvider) { + window.location = 'https://google.com/search?q=' + query; + } + }; + return (
handleSearchQuery(e)}> + {searchProviders.error && ( + {searchProviders.error} + )} setInput(e.target.value)}