@fatcherjs/middleware-json
> $ npm install @fatcherjs/middleware-json
< script src ="https://cdn.jsdelivr.net/npm/fatcher/dist/fatcher.min.js "> </ script >
< script src ="https://cdn.jsdelivr.net/npm/@fatcherjs/middleware-json/dist/index.min.js "> </ script >
< script >
Fatcher . fatcher ( 'url' , {
middlewares : [ FatcherMiddlewareJson ] ,
progressive : {
isPlaceholder : ( value ) => value . startsWith ( '$$' ) ;
}
} ) . then ( response => {
console . log ( response . skeleton ) ; // Promise Tree
console . log ( response . snapshot ) ; // Progressive Json
} ) ;
</ script >
import { fatcher } from 'fatcher' ;
import { json } from '@fatcherjs/middleware-json' ;
const res = await fatcher ( 'https://foo.bar/get' , {
middlewares : [ json ] ,
progressive : {
isPlaceholder : ( value ) => value . startsWith ( '$$' ) ;
}
} ) ;
console . log ( response . skeleton ) ; // Promise Tree
console . log ( response . snapshot ) ; // Progressive Json
Code Sandbox
import { useState } from 'react' ;
import { json } from '@fatcherjs/middleware-json' ;
import { fatcher } from 'fatcher' ;
import { use , Suspense } from 'react' ;
function delay ( ms ) {
return new Promise ( resolve => {
setTimeout ( ( ) => {
resolve ( ) ;
} , ms ) ;
} ) ;
}
async function fetchMessage ( ) {
const response = await fatcher ( 'https://test.com' , {
progressive : {
isPlaceholder : value => value . startsWith ( '$$' ) ,
} ,
middlewares : [
json ,
( ) => {
return new Response (
new ReadableStream ( {
async start ( controller ) {
controller . enqueue ( new TextEncoder ( ) . encode ( JSON . stringify ( { userInfo : '$$1' } ) ) ) ;
await delay ( 300 ) ;
controller . enqueue (
new TextEncoder ( ) . encode (
JSON . stringify ( {
$$1 : { name : 'Alice' , age : 18 } ,
} ) ,
) ,
) ;
controller . close ( ) ;
} ,
} ) ,
) ;
} ,
] ,
} ) ;
return response . skeleton ;
}
function UserInfo ( { userInfoPromise } ) {
const userInfo = use ( userInfoPromise ) ;
return userInfo ? `${ userInfo . name } (${ userInfo . age } )` : 'loading...' ;
}
function Message ( { skeleton } ) {
const data = use ( skeleton ) ;
return (
< p >
Here is the message:{ ' ' }
< Suspense fallback = { < p > ⌛Downloading UserInfo...</ p > } >
< UserInfo userInfoPromise = { data . userInfo } />
</ Suspense >
</ p >
) ;
}
export default function App ( ) {
const [ skeleton , setSkeleton ] = useState ( null ) ;
async function download ( ) {
setSkeleton ( fetchMessage ( ) ) ;
}
if ( ! skeleton ) {
return < button onClick = { download } > Download message</ button > ;
}
return (
< Suspense fallback = { < p > ⌛Downloading message...</ p > } >
< Message skeleton = { skeleton } />
</ Suspense >
) ;
}
MIT