diff options
Diffstat (limited to 'apps/Notes/hooks')
-rw-r--r-- | apps/Notes/hooks/useNotes.js | 8 | ||||
-rw-r--r-- | apps/Notes/hooks/useSort.js | 22 |
2 files changed, 30 insertions, 0 deletions
diff --git a/apps/Notes/hooks/useNotes.js b/apps/Notes/hooks/useNotes.js new file mode 100644 index 0000000..9d79034 --- /dev/null +++ b/apps/Notes/hooks/useNotes.js @@ -0,0 +1,8 @@ +import useSWR from 'swr' +import fetchJson from 'lib/fetchJson' + +export default function useNotes(){ + const { data: notes, error, mutate: mutateNotes } = useSWR('/api/notes') + + return {notes, mutateNotes, error} +} diff --git a/apps/Notes/hooks/useSort.js b/apps/Notes/hooks/useSort.js new file mode 100644 index 0000000..78c01b4 --- /dev/null +++ b/apps/Notes/hooks/useSort.js @@ -0,0 +1,22 @@ +import {useState} from 'react' +import {faSortAmountDown, faSortAmountUp} from '@fortawesome/free-solid-svg-icons' +import {FontAwesomeIcon} from '@fortawesome/react-fontawesome' + +const useSort = (d) => { + const [sort, setSort] = useState(d) + + const sortedBy = s => Math.abs(sort) === s && <FontAwesomeIcon icon={sort>0 ? faSortAmountDown : faSortAmountUp} /> + const sortBy = s => sort === s ? setSort(-1*s) : setSort(s) + const sortFn = (a, b) => { + const d = sort > 0 ? 1 : -1 + switch (Math.abs(sort)) { + case 1: return d * a.title.localeCompare(b.title) + case 2: return d * (new Date(b.created_at) - new Date(a.created_at)) + case 3: return d * (new Date(b.updated_at) - new Date(a.updated_at)) + } + } + + return [sortedBy, sortBy, sortFn] +} + +export default useSort |