William Kurniawan
Aug 5, 2020
usePosts.ts
.function usePosts() {}
export default usePosts;
use
" and it calls other Hooks, we say it is a custom Hook. The useSomething
naming convention is how our linter plugin can find bugs in the code using Hooks.import React from 'react';
interface Data {
error: Error | null;
loading: boolean;
posts: Post[];
}
interface Post {
id: string;
caption: string;
imageURL: string;
totalComments: number;
totalLikes: number;
}
function usePosts() {
const [data, setData] = React.useState<Data>({
error: null,
loading: true,
posts: [],
});
return data;
}
export default usePosts;
import React from 'react';
// Firebase
import firebase from '../firebase/client';
interface Data {
error: Error | null;
loading: boolean;
posts: Post[];
}
interface Post {
id: string;
caption: string;
imageURL: string;
totalComments: number;
totalLikes: number;
}
function usePosts() {
const [data, setData] = React.useState<Data>({
error: null,
loading: true,
posts: [],
});
React.useEffect(() => { // <--- 1
const unsubscribe = firebase // <--- 2
.firestore()
.collection('posts')
.onSnapshot(
(snapshot) => {
setData({
error: null,
loading: false,
posts: snapshot.docs.map((doc) => ({
id: doc.id,
caption: doc.data().caption,
imageURL: doc.data().imageURL,
totalComments: doc.data().totalComments,
totalLikes: doc.data().totalLikes,
})),
}); // <--- 3
},
(error) => {
setData({
error,
loading: false,
posts: [],
}); // <---4
},
);
return unsubscribe; // <--- 5
}, []);
return data;
}
export default usePosts;
useEffect
Hook to handle data fetching from Firestore. This useEffect
Hook will be executed when our custom Hook is mounted.posts
collection. This onSnapshot
function will return a function that can be used to unsubscribe from the data changes subscription.loading
state to false
and posts
to list of posts coming from Firestore. Any components that implement this usePosts
Hook will get the state updates.error
state to the error object coming from Firestore and loading
state to false
. Any components that implement this usePosts
Hook will get the state updates.usePosts
Hook is unmounted, it will unsubscribe from future incoming data changes.usePosts
Hook, you can simply call usePosts
Hook in any function components.import React from 'react';
// Hooks
import usePosts from '../hooks/usePosts';
const Component: React.FC = () => {
const { error, loading, posts } = usePosts();
console.log('error:', error);
console.log('loading:', loading);
console.log('posts:', posts);
return <div>Hello, Custom Hook!</div>;
};
export default Component;
useState
and useEffect
, but there are still others that could help you as you develop your application. The React documentation explains all the built-in Hooks very clearly.Copyright © 2020 William Kurniawan. All rights reserved.