Skip to content

Instantly share code, notes, and snippets.

@oukayuka
Last active December 7, 2019 09:30
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 oukayuka/43553625c1015c04810ddb058a15f76a to your computer and use it in GitHub Desktop.
Save oukayuka/43553625c1015c04810ddb058a15f76a to your computer and use it in GitHub Desktop.
findBook() をコールする Custom Hook
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;
@oukayuka
Copy link
Author

oukayuka commented Dec 6, 2019

findBook() のほうはこんな感じ↓

import firebase from 'firebase/app';

import { Book } from '../models/book';
import { collectionName } from '../constants';

const findBook = async (
  db: firebase.firestore.Firestore,
  id: string | null,
) => {
  if (!id) return null;

  const doc = await db
    .collection(collectionName.books)
    .doc(id)
    .get();

  return doc.exists ? ({ ...doc.data(), id: doc.id } as Book) : null;
};

export default findBook;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment