Skip to content

Commit 7d1a092

Browse files
Refactor search blog implementation on blog page
1 parent 97c0143 commit 7d1a092

File tree

1 file changed

+20
-33
lines changed

1 file changed

+20
-33
lines changed

pages/blog/index.js

Lines changed: 20 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useState } from 'react';
1+
import { useState } from 'react';
22
import BlogPostsContainer from '@/components/blog/BlogPostsContainer';
33
import SearchBar from '@/components/blog/SearchBar';
44
import Title from '@/components/snippets/Title';
@@ -8,46 +8,33 @@ import { tagToHeading } from '@/utils/blogCategories';
88
import { blogSearch } from '@/utils/search';
99

1010
export default function Blog({ posts }) {
11-
const [searchResults, setSearchResults] = useState(null);
1211
const [searchTerm, setSearchTerm] = useState('');
13-
const getPostsByTag = tag => {
14-
return posts.filter(post => post.tagList.includes(tag));
12+
13+
const filteredData = {
14+
posts: posts.slice(0, 3),
1515
};
1616

17-
useEffect(() => {
18-
setSearchResults(blogSearch(posts, searchTerm));
19-
}, [searchTerm]);
17+
if (searchTerm) {
18+
const filteredPosts = blogSearch(posts, searchTerm);
19+
filteredData.posts = filteredPosts;
20+
filteredData.heading = `${filteredPosts.length} search Results for '${searchTerm}'`;
21+
}
2022

2123
return (
2224
<>
2325
<div className={styles.blogSearch}>
24-
<Title
25-
customClass='blogTitle'
26-
title={searchResults ? '' : 'Latest Posts'}
27-
/>
28-
<SearchBar
29-
items={posts}
30-
setSearchTerm={setSearchTerm}
31-
setSearchResults={setSearchResults}
32-
/>
26+
<Title customClass='blogTitle' title={!searchTerm && 'Latest Posts'} />
27+
<SearchBar setSearchTerm={setSearchTerm} />
3328
</div>
34-
{searchResults ? (
35-
<BlogPostsContainer
36-
posts={searchResults}
37-
heading={`${searchResults.length} search Results for '${searchTerm}'`}
38-
/>
39-
) : (
40-
<>
41-
<BlogPostsContainer posts={posts.slice(0, 3)} />
42-
{Object.keys(tagToHeading).map(tag => (
43-
<BlogPostsContainer
44-
key={tag}
45-
posts={getPostsByTag(tag)}
46-
tag={tag}
47-
/>
48-
))}
49-
</>
50-
)}
29+
<BlogPostsContainer {...filteredData} />
30+
{!searchTerm &&
31+
Object.keys(tagToHeading).map(tag => (
32+
<BlogPostsContainer
33+
key={tag}
34+
posts={posts.filter(post => post.tagList.includes(tag))}
35+
tag={tag}
36+
/>
37+
))}
5138
</>
5239
);
5340
}

0 commit comments

Comments
 (0)