react-decorate-fetch
A library for React's fetch Api, very easy to separated state and view, similar to react-refetch
Installation
Supporting for react and react-native
npm i react-decorate-fetch --save
API
Interfaces
FetchConfig: Object
{
"url": string[fetch url],
"params": object[query|json],
"mapResult": function(result)[map fetch result],
"then": function(result)[hook fetch's then, and support return a new FetchConfig]
}
FetchResponse: Object
{
"status": string('success'|'error'|'pending'),
"loading": boolean,
"code": number,
"message": string('only when fetch error')
"result": any
}
FetchFunction: Function
need response State
() => ({
FetchResponseKey1: (FetchConfig),
FetchResponseKey2: (FetchConfig)
})
not need response State
() => [{
FetchConfig1(FetchConfig),
FetchConfig2(FetchConfig)
}]
connect(mapRequestToProps: Function)
It is a HOC to connect React's Component, like react-redux
mapRequestToProps(ownProps)
Map props to Fetch Requests and Responses, arguments is props, and return a Object. The key of the Object is props's name, the value of the Object allow tow type, object and function.
- if the return Object's value is a Object as
FetchConfig
, will recieve aFetchResponse
as props - if the return Object's value is a function return a Object as
FetchConfig
, will recieve aFetchFunction
as props
initConfig(options: Object, mapResponse: Function)
Init fetch config
options
Special set default fetch config, like headers、cookie、defaultQuery
mapResponse
Map Response to formate data, like json, default is res.json()
Examples
If you are use decorate fetch
@ { let userFetch = thisprops ifuserFetchstatus === "success" this else ifuserFetchstatus === 'error' this else ifuserFetchstatus === 'pending' this }
If you don't want use decorate
{ let userFetch = thisprops ifuserFetchstatus === "success" this else ifuserFetchstatus === 'error' this else ifuserFetchstatus === 'pending' this } userFetch: url: 'http://yourHost/getUserInfo/'+ propsuserId resultdatauserInfo || {}
Lazy Request
@ //OR @
Common Request
// not need response State@ // need response State@
Async Request
// not need response State@ // need response State@
Sync Request
// not need response State@ // need response State@