Skip to content

Instantly share code, notes, and snippets.

@kellenmace
Created November 17, 2021 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellenmace/2b69b13f9827b97905f965a11f8d3c21 to your computer and use it in GitHub Desktop.
Save kellenmace/2b69b13f9827b97905f965a11f8d3c21 to your computer and use it in GitHub Desktop.
Faust.js Post Filtering Example
import { useState, useMemo } from "react";
import { getNextStaticProps } from '@faustjs/next';
import { GetStaticPropsContext } from 'next';
import { client } from '../../client';
import debounce from "just-debounce-it";
export default function Blog() {
const { usePosts, useQuery } = client;
const [selectedCategory, setSelectedCategory] = useState(undefined);
const [selectedAuthor, setSelectedAuthor] = useState(undefined);
const [searchTerm, setSearchTerm] = useState('');
const [debouncedSearchTerm, setDebouncedSearchTerm] = useState('');
const posts = usePosts({
where: {
categoryIn: selectedCategory ? [selectedCategory] : [],
authorIn: selectedAuthor ? [selectedAuthor] : [],
search: debouncedSearchTerm,
}
});
const havePosts = Boolean(posts?.nodes?.length);
const categories = useQuery().categories()?.nodes;
const authors = useQuery().users()?.nodes;
const setDebouncedSearchTermMemoized = useMemo(
() => debounce(setDebouncedSearchTerm, 300),
[]
);
if (useQuery().$state.isLoading) {
return <p>Loading...</p>;
}
return (
<div>
<h1>Blog</h1>
<form onSubmit={event => event.preventDefault()}>
<label htmlFor="category-select">Category</label>
<select
id="category-select"
value={selectedCategory}
onChange={event => setSelectedCategory(event.target.value)}
>
<option key="all1" value={undefined}>
All
</option>
{categories.map(category => (
<option key={category.databaseId ?? 0} value={category?.databaseId}>
{category.name}
</option>
))}
</select>
<label htmlFor="author-select">Author</label>
<select
id="author-select"
value={selectedAuthor}
onChange={event => setSelectedAuthor(event.target.value)}
>
<option key="all" value={undefined}>
All
</option>
{authors.map(author => (
<option key={author.databaseId ?? 0} value={author?.databaseId}>
{author.name}
</option>
))}
</select>
<input
type="text"
value={searchTerm}
onChange={event => {
setSearchTerm(event.target.value);
setDebouncedSearchTermMemoized(event.target.value);
}}
placeholder="Search..."
/>
</form>
{havePosts ? (
<ul>
{posts.nodes.map(post => {
return <p key={post.databaseId ?? 0}>{post?.title()}</p>
})}
</ul>
) : (
<p>No posts found.</p>
)}
</div>
);
}
export async function getStaticProps(context: GetStaticPropsContext) {
return getNextStaticProps(context, {
Page: Blog,
client,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment