Skip to content
This repository has been archived by the owner on Dec 8, 2023. It is now read-only.

Commit

Permalink
fix: add try/catch logic
Browse files Browse the repository at this point in the history
* Adds try/catch logic to the request for search results
* Moves the setSearchResult hook outside of an if statement
  • Loading branch information
aswanson-nr committed Jul 20, 2022
1 parent 9eeed69 commit 2827045
Showing 1 changed file with 47 additions and 35 deletions.
82 changes: 47 additions & 35 deletions src/@newrelic/gatsby-theme-newrelic/pages/404.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,45 +20,14 @@ const NotFoundPage = ({ location, pageContext: { swiftypeEngineKey } }) => {
const tessen = useTessen();

const getSearchResults = useCallback(async () => {
const search = async () => {
const res = await fetch(
'https://search-api.swiftype.com/api/v1/public/engines/search.json',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
q: searchTerm,
engine_key: swiftypeEngineKey,
per_page: 5,
filters: {
page: {
type: [`docs`, `developers`, `opensource`, `quickstarts`],
document_type: [
'!views_page_menu',
'!term_page_api_menu',
'!term_page_landing_page',
],
},
},
}),
}
);

const { records } = await res.json();

return records.page;
};

let trimmedResults = null;
if (searchTerm !== null) {
const results = await search();
const trimmedResults = results.map((r) => {
const results = await search(searchTerm, swiftypeEngineKey);
trimmedResults = results.map((r) => {
return { url: r.url, title: r.title, type: r.type };
});

setSearchResult(trimmedResults);
}
setSearchResult(trimmedResults);
}, [searchTerm, swiftypeEngineKey]);

useEffect(() => {
Expand Down Expand Up @@ -224,4 +193,47 @@ displaySearchResults.propTypes = {
),
};

const search = async (searchTerm, token) => {
try {
const res = await fetch(
'https://search-api.swiftype.com/api/v1/public/engines/search.json',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
q: searchTerm,
engine_key: token,
per_page: 5,
filters: {
page: {
type: [`docs`, `developers`, `opensource`, `quickstarts`],
document_type: [
'!views_page_menu',
'!term_page_api_menu',
'!term_page_landing_page',
],
},
},
}),
}
);

if (!res.ok) {
throw new Error(
`Could not fetch related pages. ${res.status} ${res.statusText}`
);
}

const { records } = await res.json();

return records.page;
} catch (err) {
console.error(err);

return [];
}
};

export default NotFoundPage;

0 comments on commit 2827045

Please sign in to comment.