Skip to content

Commit

Permalink
fixed json
Browse files Browse the repository at this point in the history
  • Loading branch information
ShivamJoker committed Feb 10, 2021
1 parent 1a5d35a commit 0d49535
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 60 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"dexie-observable": "^3.0.0-beta.10",
"dotenv": "8.2.0",
"framer-motion": "^3.2.1",
"jsonp": "^0.2.1",
"react": "^17.0.1",
"react-circle-slider": "^1.6.2",
"react-dom": "^17.0.1",
Expand Down
123 changes: 64 additions & 59 deletions src/components/header/SearchBox.js
Original file line number Diff line number Diff line change
@@ -1,88 +1,90 @@
import React, { useContext, useState, useEffect, useCallback } from "react";
import { withRouter } from "react-router-dom";
import React, { useContext, useState, useEffect, useCallback } from 'react';
import { withRouter } from 'react-router-dom';

import {
InputBase,
IconButton,
Popper,
CircularProgress,
Grid
} from "@material-ui/core";
import { ArrowBack } from "@material-ui/icons";
Grid,
} from '@material-ui/core';
import { ArrowBack } from '@material-ui/icons';

import { GlobalContext } from "../GlobalState";
import suggestSearch from "../../apis/suggestSearch";
import AutoSearchResult from "./AutoSearchResult";
import youtubeSearch from "../../apis/youtubeSearch";
const jsonp = require('jsonp')
import { GlobalContext } from '../GlobalState';
import suggestSearch from '../../apis/suggestSearch';
import AutoSearchResult from './AutoSearchResult';
import youtubeSearch from '../../apis/youtubeSearch';

import jsonp from 'jsonp';

const SearchBox = ({ history, location }) => {
let params = new URLSearchParams(location.search);

const [{ searchState }, dispatch] = useContext(GlobalContext);

const setSearchState = useCallback(
data => {
dispatch({ type: "setSearchState", snippet: data });
(data) => {
dispatch({ type: 'setSearchState', snippet: data });
},
[dispatch]
);

const setSearchResult = useCallback(
data => {
(data) => {
console.log(data);
dispatch({ type: "setSearchResult", snippet: data });
dispatch({ type: 'setSearchResult', snippet: data });
},
[dispatch]
);

const [searchQuery, setSearchQuery] = useState("");
const [autoSearchData, setAutoSearch] = useState("");
const [searchQuery, setSearchQuery] = useState('');
const [autoSearchData, setAutoSearch] = useState('');

const [ytSearchQuery, setYtSearchQuery] = useState(null);

// toggle popper
const [isPopperOpen, setPopper] = useState(true);

console.log("search box re rendered");
console.log('search box re rendered');

// get back the selected search data
const onSearchSelect = result => {
const onSearchSelect = (result) => {
setSearchQuery(result);
setYtSearchQuery(result);
setSearchState("searching");
history.push({ pathname: "/search", search: `?q=${result}` });
setSearchState('searching');
history.push({ pathname: '/search', search: `?q=${result}` });
};

// when user hits enter then also fetch the data from yt api
const onSearchSubmit = e => {
const onSearchSubmit = (e) => {
e.preventDefault();
console.log(e.target.lastChild);
e.target.lastChild.lastChild.blur();
setSearchState("searching");
setSearchState('searching');
setYtSearchQuery(searchQuery);
history.push({ pathname: "/search", search: `?q=${searchQuery}` });
history.push({ pathname: '/search', search: `?q=${searchQuery}` });
};

const debounce = (func, delay = 150) => {
let timeId;
return function() {
let context = this, args = arguments;
return function () {
let context = this,
args = arguments;
clearTimeout(timeId);
timeId = setTimeout(() => {
func.apply(context, args);
}, delay);
}
}
};
};

const getQueryString = queryParams => {
const getQueryString = (queryParams) => {
let queryStr = '';
for(let param in queryParams)
for (let param in queryParams)
queryStr += `${param}=${queryParams[param]}&`;

// remove the last &
return queryStr.slice(0, -1);
}
};

// for controlled input change
const onChange = (event) => {
Expand All @@ -95,43 +97,46 @@ const SearchBox = ({ history, location }) => {
// get autocomplete data form api
const getAutocomplete = () => {
suggestSearch.params.q = searchQuery;
jsonp(suggestSearch.baseURL + getQueryString(suggestSearch.params)
, null, (err, response) => {
setAutoSearch(response[1]);
});
jsonp(
suggestSearch.baseURL + getQueryString(suggestSearch.params),
null,
(err, response) => {
setAutoSearch(response[1]);
}
);
};

// get youtube search result from api
useEffect(() => {
const searchYt = async data => {
const res = await youtubeSearch.get("/search", {
const searchYt = async (data) => {
const res = await youtubeSearch.get('/search', {
params: {
q: data,
maxResults: 15
}
maxResults: 15,
},
});
setSearchResult(res.data.items);
setSearchState("completed");
setSearchState('completed');
};
// only search if there is any value
if (ytSearchQuery && ytSearchQuery !== "") {
if (ytSearchQuery && ytSearchQuery !== '') {
searchYt(ytSearchQuery);
}
// console.log(ytSearchQuery);
}, [ytSearchQuery, setSearchResult, setSearchState]);

useEffect(() => {
console.log("search state", searchState);
console.log('search state', searchState);
}, [searchState]);

useEffect(() => {
// Listen for changes to the current location.
const query = params.get("q");
const query = params.get('q');
if (query) {
setYtSearchQuery(query);
setSearchQuery(query);
setSearchState("searching");
console.log("changing query to", query);
setSearchState('searching');
console.log('changing query to', query);
}

// const unlisten = history.listen(location => {
Expand All @@ -151,39 +156,39 @@ const SearchBox = ({ history, location }) => {

const popperResult = () => {
switch (searchState) {
case "searching":
case 'searching':
return (
<Grid
style={{ height: "100vh" }}
style={{ height: '100vh' }}
container
justify="center"
alignItems="center"
>
<CircularProgress />
</Grid>
);
case "clicked":
case 'clicked':
return (
<AutoSearchResult
results={autoSearchData}
onSearchSelect={onSearchSelect}
/>
);
case "completed":
case 'completed':
setPopper(false);
break;
default:
break;
}
console.log("Function ran");
console.log('Function ran');
};

return (
<>
<IconButton
onClick={() => {
setSearchState("home");
if (history.location.pathname === "/search") {
setSearchState('home');
if (history.location.pathname === '/search') {
history.goBack();
}
// only go back if u have searched something
Expand All @@ -193,17 +198,17 @@ const SearchBox = ({ history, location }) => {
>
<ArrowBack />
</IconButton>
<form style={{ width: "100%" }} onSubmit={e => onSearchSubmit(e)}>
<form style={{ width: '100%' }} onSubmit={(e) => onSearchSubmit(e)}>
<InputBase
fullWidth
placeholder="Search..."
autoFocus
style={{ color: "#fff", paddingLeft: "16px" }}
style={{ color: '#fff', paddingLeft: '16px' }}
value={searchQuery}
onChange={onChange}
// on click we will show popper
onClick={() => {
setSearchState("clicked");
setSearchState('clicked');
setPopper(true);
}}
/>
Expand All @@ -212,13 +217,13 @@ const SearchBox = ({ history, location }) => {
<Popper
className="searchPopper"
open={isPopperOpen}
anchorEl={document.getElementById("navbar")}
anchorEl={document.getElementById('navbar')}
popperOptions={{
modifiers: {
preventOverflow: {
padding: 0
}
}
padding: 0,
},
},
}}
placement="bottom"
>
Expand Down
9 changes: 8 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3975,7 +3975,7 @@ data-urls@^2.0.0:
whatwg-mimetype "^2.3.0"
whatwg-url "^8.0.0"

[email protected], debug@^2.2.0, debug@^2.3.3, debug@^2.6.0, debug@^2.6.9:
[email protected], debug@^2.1.3, debug@^2.2.0, debug@^2.3.3, debug@^2.6.0, debug@^2.6.9:
version "2.6.9"
resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"
integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==
Expand Down Expand Up @@ -6922,6 +6922,13 @@ jsonfile@^6.0.1:
optionalDependencies:
graceful-fs "^4.1.6"

jsonp@^0.2.1:
version "0.2.1"
resolved "https://registry.yarnpkg.com/jsonp/-/jsonp-0.2.1.tgz#a65b4fa0f10bda719a05441ea7b94c55f3e15bae"
integrity sha1-pltPoPEL2nGaBUQep7lMVfPhW64=
dependencies:
debug "^2.1.3"

jsprim@^1.2.2:
version "1.4.1"
resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2"
Expand Down

0 comments on commit 0d49535

Please sign in to comment.