east-hooks
v0.5.1
Published
React Hooks สำหรับ API Request และ UI components ง่ายๆ เพียงไม่กี่บรรทัด
Maintainers
Readme
east-hooks
React hooks สำหรับงานที่ใช้บ่อยในแอปพลิเคชัน React
การติดตั้ง (Installation)
npm install east-hooks
# หรือ
yarn add east-hooksการติดตั้ง Dependencies เพิ่มเติมสำหรับ AuthProvider
สำคัญ: หากต้องการใช้งาน AuthProvider คุณจำเป็นต้องติดตั้ง dependencies เพิ่มเติมดังนี้:
npm install next-auth firebase
# หรือ
yarn add next-auth firebaseหากไม่ติดตั้ง dependencies เหล่านี้ จะเกิดข้อผิดพลาด เช่น Cannot find module 'next-auth/react' หรือ Cannot find module 'firebase/auth'
Hooks ที่มีให้ใช้งาน
useFetch
Hook สำหรับการส่งคำขอ API พร้อมกับจัดการสถานะการโหลดและข้อผิดพลาดโดยอัตโนมัติ รวมถึงการแสดง Alert และ Modal
วิธีใช้งานพื้นฐาน
import { useFetch } from 'east-hooks';
const MyComponent = () => {
const { data, loading, error, trigger } = useFetch<ResponseType>(
'POST', // HTTP method
'/api/users', // URL endpoint
{ alert: true }, // options
{ name: 'John', age: 30 } // body data (จะถูกแปลงเป็น JSON โดยอัตโนมัติ)
);
const handleSubmit = () => {
trigger(); // เรียกใช้ API
};
return (
<div>
<button onClick={handleSubmit} disabled={loading}>
{loading ? 'กำลังส่งข้อมูล...' : 'บันทึกข้อมูล'}
</button>
{error && <p>เกิดข้อผิดพลาด: {error.message}</p>}
</div>
);
};รายละเอียดพารามิเตอร์
useFetch<T>(
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
url: string,
options?: RequestOptions,
bodyData?: any
)method: HTTP method (GET, POST, PUT, DELETE)url: URL ปลายทางของ APIoptions: ตัวเลือกเพิ่มเติม (ไม่จำเป็นต้องระบุ)interface RequestOptions { alert?: boolean; // เปิดใช้งานการแจ้งเตือนแบบ toast notification headers?: Record<string, string>; // HTTP headers เพิ่มเติม immediate?: boolean; // เรียกใช้ API ทันทีที่ component ถูกโหลด confirmModal?: { // แสดง modal ยืนยันก่อนส่ง API request title: string; // หัวข้อของ confirm modal content: string; // เนื้อหาของ confirm modal }; notificationModal?: { // แสดง modal แจ้งเตือนหลังได้ผลลัพธ์จาก API title?: string; // หัวข้อของ notification modal content?: string; // เนื้อหาของ notification modal duration?: number; // ระยะเวลาแสดง modal ในหน่วยมิลลิวินาที (ms) (ค่าเริ่มต้น: 5000) }; }bodyData: ข้อมูลที่จะส่งไปกับคำขอ (เฉพาะ POST, PUT, DELETE)
ค่าที่ return กลับมา
{
data: T | null; // ข้อมูลที่ได้รับจาก API
loading: boolean; // สถานะการโหลด (true/false)
error: Error | null; // ข้อผิดพลาดที่เกิดขึ้น (Error object หรือ null)
trigger: () => Promise<void>; // ฟังก์ชันสำหรับเรียกใช้ API
}ตัวอย่างการใช้งาน
- การใช้งานพื้นฐาน
const { data, loading, error, trigger } = useFetch<User[]>('GET', '/api/users');
// เรียกใช้งาน
trigger();- การใช้งานกับ Alert (Toast Notification)
const { trigger } = useFetch('POST', '/api/users',
{ alert: true },
{ name: 'John' }
);
// จะแสดง toast notification เมื่อ API response มีรูปแบบดังนี้
// { message: "บันทึกสำเร็จ", description: "เพิ่มผู้ใช้ใหม่แล้ว", status: "success" }- การใช้งานกับ Confirm Modal
const { trigger } = useFetch('DELETE', '/api/users/1', {
confirmModal: {
title: 'ยืนยันการลบ',
content: 'คุณต้องการลบข้อมูลนี้ใช่หรือไม่?'
}
});
// เมื่อเรียกใช้ trigger() จะแสดง confirm modal ก่อน
// ถ้ากด "ยืนยัน" จะทำการส่ง request
// ถ้ากด "ยกเลิก" จะยกเลิกการส่ง request- การใช้งานกับ Notification Modal
const { trigger } = useFetch('PUT', '/api/users/1', {
notificationModal: {
title: 'แก้ไขข้อมูลสำเร็จ',
content: 'ระบบได้บันทึกการเปลี่ยนแปลงเรียบร้อยแล้ว',
duration: 3000 // แสดงเป็นเวลา 3 วินาที
}
}, { name: 'Updated Name' });
// เมื่อ API ทำงานเสร็จจะแสดง notification modal
// พร้อมนับถอยหลังและปุ่มปิด- การใช้งานทั้ง Confirm Modal และ Notification Modal
const { trigger } = useFetch('POST', '/api/users', {
confirmModal: {
title: 'ยืนยันการเพิ่มข้อมูล',
content: 'คุณต้องการเพิ่มข้อมูลผู้ใช้ใหม่ใช่หรือไม่?'
},
notificationModal: {
title: 'เพิ่มข้อมูลสำเร็จ',
content: 'ระบบได้บันทึกข้อมูลผู้ใช้ใหม่เรียบร้อยแล้ว',
duration: 5000 // แสดงเป็นเวลา 5 วินาที
}
}, { name: 'John', email: '[email protected]' });
// 1. แสดง confirm modal เมื่อเรียกใช้ trigger()
// 2. ถ้ากด "ยืนยัน" จะทำการส่ง request
// 3. เมื่อ API ทำงานเสร็จจะแสดง notification modal- การใช้งานกับ FormData
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
trigger();
};
const { trigger } = useFetch('POST', '/api/upload',
{ alert: true },
formData // ส่งเป็น FormData โดยตรง (จะไม่แปลงเป็น JSON)
);useAuth
Hook สำหรับจัดการการเข้าสู่ระบบ (Authentication) ด้วย Next-Auth และ Firebase Authentication
วิธีใช้งานพื้นฐาน
import { useAuth } from 'east-hooks';
const ProfileComponent = () => {
const { user, status, signIn, signOut } = useAuth();
if (status === 'loading') {
return <p>กำลังโหลด...</p>;
}
if (status === 'unauthenticated') {
return (
<div>
<p>กรุณาเข้าสู่ระบบ</p>
<button onClick={() => signIn('google_firebase')}>
เข้าสู่ระบบด้วย Google
</button>
<button onClick={() => signIn('discord')}>
เข้าสู่ระบบด้วย Discord
</button>
</div>
);
}
return (
<div>
<h2>ยินดีต้อนรับ {user?.name}</h2>
<img src={user?.image} alt={user?.name} />
<p>อีเมล: {user?.email}</p>
<button onClick={signOut}>ออกจากระบบ</button>
</div>
);
};ค่าที่ return กลับมา
{
user: User | null; // ข้อมูลผู้ใช้ที่เข้าสู่ระบบ หรือ null ถ้ายังไม่ได้เข้าสู่ระบบ
status: 'authenticated' | 'loading' | 'unauthenticated'; // สถานะการเข้าสู่ระบบ
updateUser: (userData: Partial<User>, callback?: () => void) => void; // ฟังก์ชันสำหรับอัพเดตข้อมูลผู้ใช้
signIn: (provider: 'google_firebase' | 'discord') => Promise<void>; // ฟังก์ชันสำหรับเข้าสู่ระบบ
signOut: () => Promise<void>; // ฟังก์ชันสำหรับออกจากระบบ
}ฟังก์ชันสะดวกสำหรับใช้งานนอก Component
นอกจาก useAuth hook แล้ว ยังมีฟังก์ชันอื่นๆ ที่สามารถเรียกใช้ได้จากที่ไหนก็ได้:
import { getUser, getStatus, signIn, signOut, updateUser } from 'east-hooks';
// ดึงข้อมูลผู้ใช้ปัจจุบัน
const currentUser = getUser();
// ดูสถานะการเข้าสู่ระบบ
const authStatus = getStatus();
// เข้าสู่ระบบด้วย Google
await signIn('google_firebase');
// ออกจากระบบ
await signOut();
// อัพเดตข้อมูลผู้ใช้
updateUser({ name: 'New Name' }, () => {
console.log('อัพเดตข้อมูลเรียบร้อย');
});Providers
HooksProvider (แนะนำให้ใช้)
Provider ตัวเดียวที่รวมความสามารถของทั้ง AlertProvider, ModalProvider และ AuthProvider (ถ้าเปิดใช้งาน) ไว้ด้วยกัน
วิธีใช้งาน HooksProvider
import { HooksProvider } from 'east-hooks';
// กำหนด Firebase configuration
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID',
measurementId: 'YOUR_MEASUREMENT_ID'
};
const App = () => {
return (
<HooksProvider
withAuth={true}
firebaseConfig={firebaseConfig}
>
<YourApp />
</HooksProvider>
);
};
export default App;วิธีใช้งาน HooksProvider พร้อม AuthProvider
import { HooksProvider } from 'east-hooks';
// กำหนด Firebase configuration
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID',
measurementId: 'YOUR_MEASUREMENT_ID'
};
const App = () => {
return (
<HooksProvider
withAuth={true}
firebaseConfig={firebaseConfig}
>
<YourApp />
</HooksProvider>
);
};
export default App;เมื่อใช้ HooksProvider คุณสามารถใช้งาน useAlert, useModal และ useAuth (ถ้าเปิดใช้ withAuth) hooks ได้ทันที:
import { useAlert, useModal, useFetch, useAuth } from 'east-hooks';
const YourComponent = () => {
const { showAlert } = useAlert();
const { showConfirmModal, showNotificationModal } = useModal();
const { user, signIn, signOut } = useAuth(); // ใช้ได้เมื่อเปิด withAuth={true}
// ใช้งาน useFetch ได้พร้อมความสามารถ alert, confirmModal และ notificationModal
const { trigger } = useFetch('POST', '/api/users', {
alert: true,
confirmModal: {
title: 'ยืนยัน',
content: 'คุณต้องการทำรายการนี้ใช่หรือไม่?'
}
});
return (
<div>
<button onClick={() => trigger()}>บันทึกข้อมูล</button>
{user ? (
<button onClick={signOut}>ออกจากระบบ</button>
) : (
<button onClick={() => signIn('google_firebase')}>
เข้าสู่ระบบด้วย Google
</button>
)}
</div>
);
};AuthProvider
Provider สำหรับจัดการการเข้าสู่ระบบด้วย Next-Auth และ Firebase Authentication
การตั้งค่าก่อนใช้งาน
สำคัญ: ก่อนใช้งาน AuthProvider คุณต้องติดตั้ง dependencies เพิ่มเติมให้เรียบร้อย:
npm install next-auth firebase
# หรือ
yarn add next-auth firebaseหมายเหตุ: หากไม่ติดตั้ง dependencies เหล่านี้ จะเกิดข้อผิดพลาด เช่น Cannot find module 'next-auth/react' หรือ Cannot find module 'firebase/auth'
และต้องตั้งค่า Firebase และ Next-Auth ใน Next.js app ของคุณก่อน:
ตั้งค่า Firebase
- กำหนด Firebase configuration จาก Firebase Console และส่งเข้าไปยัง AuthProvider
- ตัวอย่าง Firebase configuration:
const firebaseConfig = { apiKey: 'YOUR_API_KEY', authDomain: 'YOUR_AUTH_DOMAIN', projectId: 'YOUR_PROJECT_ID', storageBucket: 'YOUR_STORAGE_BUCKET', messagingSenderId: 'YOUR_MESSAGING_SENDER_ID', appId: 'YOUR_APP_ID', measurementId: 'YOUR_MEASUREMENT_ID' };ตั้งค่า Next-Auth
- สร้างไฟล์
app/api/auth/[...nextauth]/route.ts(สำหรับ Next.js App Router) - หรือ
pages/api/auth/[...nextauth].ts(สำหรับ Next.js Pages Router) - ตั้งค่า providers และ callbacks ที่จำเป็น
- สร้างไฟล์
วิธีใช้งาน AuthProvider
- ครอบ component ที่ต้องการใช้งาน auth ด้วย
AuthProviderWrapperและส่งfirebaseConfig:
import { AuthProviderWrapper } from 'east-hooks';
// กำหนด Firebase configuration
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID',
measurementId: 'YOUR_MEASUREMENT_ID'
};
const App = () => {
return (
<AuthProviderWrapper firebaseConfig={firebaseConfig}>
<YourComponent />
</AuthProviderWrapper>
);
};- ใช้งาน
useAuthhook เพื่อจัดการการเข้าสู่ระบบ:
import { useAuth } from 'east-hooks';
const YourComponent = () => {
const { user, status, signIn, signOut, updateUser } = useAuth();
return (
<div>
{status === 'authenticated' ? (
<>
<p>สวัสดี, {user?.name}</p>
<button onClick={signOut}>ออกจากระบบ</button>
</>
) : (
<button onClick={() => signIn('google_firebase')}>
เข้าสู่ระบบด้วย Google
</button>
)}
</div>
);
};AlertProvider
Provider สำหรับแสดง toast notification ที่มุมบนขวาของหน้าจอ
วิธีใช้งาน AlertProvider
- ครอบ component ที่ต้องการใช้งาน alert ด้วย
AlertProvider:
import { AlertProvider } from 'east-hooks';
const App = () => {
return (
<AlertProvider>
<YourComponent />
</AlertProvider>
);
};- ใช้งาน
useAlerthook เพื่อแสดง alert:
import { useAlert } from 'east-hooks';
const YourComponent = () => {
const { showAlert } = useAlert();
const handleClick = () => {
showAlert({
message: 'บันทึกสำเร็จ',
description: 'ระบบได้บันทึกข้อมูลเรียบร้อยแล้ว',
type: 'success', // 'success', 'info', 'warning', 'error'
duration: 3000 // เวลาแสดงในหน่วย ms (ค่าเริ่มต้น: 3000)
});
};
return <button onClick={handleClick}>แสดง Alert</button>;
};ModalProvider
Provider สำหรับแสดง modal แบบ confirm และ notification
วิธีใช้งาน ModalProvider
- ครอบ component ที่ต้องการใช้งาน modal ด้วย
ModalProvider:
import { AlertProvider, ModalProvider } from 'east-hooks';
const App = () => {
return (
<AlertProvider>
<ModalProvider>
<YourComponent />
</ModalProvider>
</AlertProvider>
);
};- ใช้งาน
useModalhook เพื่อแสดง modal:
import { useModal } from 'east-hooks';
const YourComponent = () => {
const { showConfirmModal, showNotificationModal } = useModal();
const handleShowConfirm = () => {
showConfirmModal(
'ยืนยันการลบ', // title
'คุณต้องการลบข้อมูลนี้ใช่หรือไม่?', // content
() => {
// ฟังก์ชันที่จะทำงานเมื่อกดปุ่ม "ยืนยัน"
console.log('ผู้ใช้กดยืนยัน');
// ทำการลบข้อมูล...
},
() => {
// ฟังก์ชันที่จะทำงานเมื่อกดปุ่ม "ยกเลิก" (optional)
console.log('ผู้ใช้กดยกเลิก');
}
);
};
const handleShowNotification = () => {
showNotificationModal(
'บันทึกสำเร็จ', // title
'ระบบได้บันทึกข้อมูลเรียบร้อยแล้ว', // content
5000 // duration (ms) (optional, ค่าเริ่มต้น: 5000)
);
};
return (
<div>
<button onClick={handleShowConfirm}>แสดง Confirm Modal</button>
<button onClick={handleShowNotification}>แสดง Notification Modal</button>
</div>
);
};การใช้งาน Providers ร่วมกัน
แนะนำ: ใช้ HooksProvider ซึ่งจัดการรวม providers ทั้งหมดไว้ในที่เดียว:
import { HooksProvider } from 'east-hooks';
// กำหนด Firebase configuration
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID',
measurementId: 'YOUR_MEASUREMENT_ID'
};
const App = () => {
return (
<HooksProvider
withAuth={true}
firebaseConfig={firebaseConfig}
>
<YourApp />
</HooksProvider>
);
};
export default App;ทางเลือก: หากต้องการจัดการ providers แยกกัน:
import { AlertProvider, ModalProvider, AuthProviderWrapper } from 'east-hooks';
// กำหนด Firebase configuration
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID',
measurementId: 'YOUR_MEASUREMENT_ID'
};
const App = () => {
return (
<AuthProviderWrapper firebaseConfig={firebaseConfig}>
<AlertProvider>
<ModalProvider>
<YourApp />
</ModalProvider>
</AlertProvider>
</AuthProviderWrapper>
);
};License
MIT
