This commit is contained in:
2026-03-13 17:23:37 +07:00
parent 25111ff10e
commit 2d2bf85f83
43 changed files with 2094 additions and 448 deletions

View File

@@ -1,14 +1,13 @@
'use client';
import { useEffect, useState } from 'react';
import { MSWContext } from '@/contexts/MSWContext';
/**
* Khởi động MSW browser worker trong development.
* Block render cho đến khi worker ready để tránh race condition
* (requests gửi trước khi MSW sẵn sàng sẽ bị passthrough → "Failed to fetch").
* Cung cấp trạng thái ready qua MSWContext để các hook fetch
* (useApiData) tự chờ MSW sẵn sàng trước khi gọi API.
*/
const MSWProvider = ({ children }: { children: React.ReactNode }) => {
// Production: render ngay (NODE_ENV !== 'development' → ready = true)
// Development: chờ worker.start() xong rồi mới render
const [ready, setReady] = useState(process.env.NODE_ENV !== 'development');
useEffect(() => {
@@ -23,12 +22,11 @@ const MSWProvider = ({ children }: { children: React.ReactNode }) => {
.then(() => setReady(true))
.catch((err) => {
console.error('[MSW] Failed to start worker:', err);
setReady(true); // vẫn render dù worker fail
setReady(true);
});
}, []);
if (!ready) return null;
return <>{children}</>;
return <MSWContext.Provider value={ready}>{children}</MSWContext.Provider>;
};
export default MSWProvider;