@@ -5,21 +5,39 @@ import {
55 unstable_createContext ,
66} from "react-router" ;
77import { type ToastMessage , getToast as getToastPrimitive } from ".." ;
8+ import { FLASH_SESSION } from "../schema" ;
9+ import { sessionStorage } from "../session" ;
810
911const toastContext = unstable_createContext < ToastMessage | null > ( null ) ;
12+ const sessionToastContext = unstable_createContext < ToastMessage | null > ( null ) ;
1013
1114export function unstable_toastMiddleware ( props ?: { customSession ?: SessionStorage } ) : unstable_MiddlewareFunction {
1215 const { customSession } = props || { } ;
13-
16+ const sessionToUse = customSession || sessionStorage ;
1417 return async function toastMiddleware ( { request, context } , next ) {
1518 const { toast, headers } = await getToastPrimitive ( request , customSession ) ;
19+
1620 context . set ( toastContext , toast ?? null ) ;
21+ // Call the next middleware or route handler
1722 const res = await next ( ) ;
23+
1824 if ( res instanceof Response && toast ) {
19- res . headers . append ( "Set-Cookie" , headers . get ( "Set-Cookie" ) || "" ) ;
25+ res . headers . append ( "Set-Cookie" , headers . get ( "Set-Cookie" ) ?? "" ) ;
2026 }
27+ const toastToSet = context . get ( sessionToastContext ) ;
28+
29+ if ( res instanceof Response && toastToSet ) {
30+ const session = await sessionToUse . getSession ( request . headers . get ( "Cookie" ) ) ;
31+ session . flash ( FLASH_SESSION , { toast : toastToSet } ) ;
32+ res . headers . append ( "Set-Cookie" , await sessionToUse . commitSession ( session ) ) ;
33+ }
34+
2135 return res ;
2236 } ;
2337}
2438
39+ export const setToast = ( context : unstable_RouterContextProvider , toast : ToastMessage | null ) => {
40+ context . set ( sessionToastContext , toast ) ;
41+ } ;
42+
2543export const getToast = ( context : unstable_RouterContextProvider ) => context . get ( toastContext ) ;
0 commit comments