Last active
December 7, 2019 09:30
-
-
Save oukayuka/43553625c1015c04810ddb058a15f76a to your computer and use it in GitHub Desktop.
findBook() をコールする Custom Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useContext, useEffect, useRef, useState } from 'react'; | |
import { Book } from 'domains/mangarel/models/book'; | |
import findBook from 'domains/mangarel/services/find-book'; | |
import { FirebaseContext } from 'contexts'; | |
const useFindBook = (id: string) => { | |
const [book, setBook] = useState<Book>(); | |
const [isLoading, setIsLoading] = useState(false); | |
const [error, setError] = useState<Error | null>(null); | |
const firebaseRef = useRef(useContext(FirebaseContext)); | |
useEffect(() => { | |
const { db } = firebaseRef.current; | |
if (!db) throw new Error('Firestore is not initialized'); | |
const load = async () => { | |
setIsLoading(true); | |
try { | |
const bookData = await findBook(db, id); | |
if (bookData) { | |
setBook(bookData); | |
setError(null); | |
} else { | |
setError(new Error('404 book not found')); | |
} | |
} catch (err) { | |
setError(err); | |
} finally { | |
setIsLoading(false); | |
} | |
}; | |
load(); | |
}, [id]); | |
return { book, isLoading, error }; | |
}; | |
export default useFindBook; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
findBook() のほうはこんな感じ↓