remote data
1.0.0
用於從遠端來源(包括 HTTP)獲取資料的微型(小於 450 位元組)工具。有關遠距數據為何有幫助的詳細文章,請閱讀這篇文章。
$ npm install @roebuk/remote-data
< script type =" module " >
import RemoteData from 'https://cdn.skypack.dev/@roebuk/remote-data' ;
</ script >
< script src =" https://unpkg.com/@roebuk/remote-data " > </ script >
API文件
import * as RemoteData from '@roebuk/remote-data' ;
// Set the initial state
var remoteUsers = RemoteData . NotAsked ( ) ;
// An interaction starts off the request
remoteUsers = RemoteData . Loading ( ) ;
// Once the request is complete,
// it will either be in a `Success` or `Failure` state.
remoteUsers = await fetch ( '/api/users' )
. then ( res => res . json ( ) )
. then ( users => RemoteData . Success ( users ) )
. catch ( err => RemoteData . Failure ( err ) ) ;
// "Pattern match" on the RemoteData type and extract the current state.
// The return value of the functions should all be of the same type.
RemoteData . match ( {
notAsked : ( ) => 'Not Requested the data'
loading : ( ) = > 'Loading...'
success : users => `Loaded ${ users . length } users` ,
failed : err => `Something when wrong. Details: ${ err . message } `
} , remoteUsers ) ;
StackBlitz 上的 React 和遠端數據
npm ci
npm run build
npm t