Skip to content

Commit

Permalink
build: build production v0.1.1 at 2019-12-12 02:20:34
Browse files Browse the repository at this point in the history
  • Loading branch information
誌小強 authored and 誌小強 committed Dec 12, 2019
0 parents commit 9345a5b
Show file tree
Hide file tree
Showing 9 changed files with 784 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
196 changes: 196 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
# @jzone/react-request-hook

> React hook for custom request,compatible with various lib, support redux
## Features

- Custom request support
- 0 dependency
- Coming soon to support TypeScript

## Usage

### Basic Usage

```jsx
import React, { useEffect } from 'react'
import useFetchData from '@jzone/react-request-hook'
import axios from '@/utils/axios'

export default function TestPages (props) {
const [{ data, isLoading, error }, fetchData] = useFetchData(data => axios.get('/xxx', { params: data }))

useEffect(() => {
fetchData()
}, [fetchData])

if (!data) {
return !error ? <div>loading...</div> : <div>error</div>
}

return <div>
<p>hello useFetchData</p>
<span onClick={() => fetchData({ a: 3 })}>onClick</span>
</div>
}
```

### Custom Hooks

```js
// hook/index.js
import React from 'react'
import useFetchData from '@jzone/react-request-hook'
import axios from 'axios'
/**
* @param {*} url url
* @param {*} initState setInit state, defaultValue: undefined
* @return {array} [state, memoizedFetchDateApi] state: { data, isLoading, error, ... }
*/
export const useFetchDataGet = (url, initState) => {
const [state, memoizedFetchDateApi] = useFetchData(data => axios.get(url, { params: data }), initState)

return [state, memoizedFetchDateApi]
}

/**
* @param {*} url url
* @param {*} initState setInit state, defaultValue: undefined
* @return {array} [state, memoizedFetchDateApi] state: { data, isLoading, error, ... }
*/
export const useFetchDataPost = (url, initState) => {
const [state, memoizedFetchDateApi] = useFetchData(data => axios.post(url, data), initState)

return [state, memoizedFetchDateApi]
}
```

### GET

```jsx
import React, { useEffect } from 'react'
import useFetchData from '@jzone/react-request-hook'
import axios from '@/utils/axios'
import { useFetchDataGet } from '@/hook'

export default function TestPages (props) {
const [{ data, isLoading, error }, fetchData] = useFetchData(data => axios.get('/xxx', { params: data }))
// or
// const [{ data, isLoading, error }, fetchData] = useFetchDataGet('/xxx')
useEffect(() => {
fetchData()
}, [fetchData])

if (!data) {
return !error ? <div>loading...</div> : <div>error</div>
}

return <div>
<p>hello useFetchData</p>
<span onClick={() => fetchData({ a: 3 })}>onClick</span>
</div>
}
```

### POST

```jsx
import React, { useEffect } from 'react'
import useFetchData from '@jzone/react-request-hook'
import axios from '@/utils/axios'
import { useFetchDataPost } from '@/hook'

export default function TestPages (props) {
const [{ data, isLoading, error }, fetchData] = useFetchData(data => axios.post('/xxx', data))
// or
// const [{ data, isLoading, error }, fetchData] = useFetchDataPost('/xxx')
useEffect(() => {
fetchData()
}, [fetchData])

if (!data) {
return !error ? <div>loading...</div> : <div>error</div>
}

return <div>
<p>hello useFetchDataGet</p>
<span onClick={() => fetchData({ a: 3 })}>onClick</span>
</div>
}
```

### Batch Request

```jsx
function BatchRequest () {
const batchFetchData = (data) => Promise.all([request1(data), request2(data)])
const [{ loading, error, data }, fetchData] = useFetchData(batchFetchData)

useEffect(() => { fetchData() }, [fetchData])

if (loading) return 'loading...'
if (error) return 'error'

const [res1, res2] = data

return (
<div>
<div>{res1}</div>
<div>{res2}</div>
<button onClick={() => fetchData({ a: 3 })}>refetch batch</button>
</div>
)
}
```

## API

### Common API

参数 | 说明 | 类型 | 默认值
----- | ---- | --- | ---
state.data | 接口返回值 | any | {}
state.isLoading | 是否加载中 | Boolean or undefined | undefined
state.error | 接口请求错误 | any | null
fetch | 绑定state的请求方法,使用时fetch() 或者 fetch(data) | function(data?) |
initState | 初始/默认state, e.g: { isLoader: true } 初始为加载中 | Object |

### useFetchData

```js
const [state, fetch] = useFetchData(requestFn[, initState])
```

参数 | 说明 | 类型 | 默认值
----- | ---- | --- | ---
requestFn | 自定义请求方法 | function(data?) |

```js
requestFn e.g:

(data) => fetch('/xxx', { method: 'POST', body: data })
(data) => axios.get('/xxx', {params: data})
(data) => axios.post('/xxx', {params: data})
(data) => Promise(req1(data), req2(data))
...
```

### useFetchDataGet

```js
const [state, fetch] = useFetchDataGet(url[, initState])
```

参数 | 说明 | 类型 | 默认值
----- | ---- | --- | ---
url | 请求地址 | String |

### useFetchDataPost

```js
const [state, fetch] = useFetchDataPost(url[, initState])
```

参数 | 说明 | 类型 | 默认值
----- | ---- | --- | ---
url | 请求地址 | String |
24 changes: 24 additions & 0 deletions example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import React from 'react'
import axios from 'axios'
import useFetchData from './index'
/**
* @param {*} url url
* @param {*} initState setInit state, defaultValue: undefined
* @return {array} [state, memoizedFetchDateApi] state: { data, isLoading, error, ... }
*/
export const useFetchDataGet = (url, initState) => {
const [state, memoizedFetchDateApi] = useFetchData(data => axios.get(url, { params: data }), initState)

return [state, memoizedFetchDateApi]
}

/**
* @param {*} url url
* @param {*} initState setInit state, defaultValue: undefined
* @return {array} [state, memoizedFetchDateApi] state: { data, isLoading, error, ... }
*/
export const useFetchDataPost = (url, initState) => {
const [state, memoizedFetchDateApi] = useFetchData(data => axios.post(url, data), initState)

return [state, memoizedFetchDateApi]
}
55 changes: 55 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import React, { useReducer, useCallback } from 'react'

const FETCH_REQUEST = 'FETCH_REQUEST'
const FETCH_SUCCESS = 'FETCH_SUCCESS'
const FETCH_FAILURE = 'FETCH_FAILURE'

const fetchDataReducer = (initState, action) => {
switch (action.type) {
case FETCH_REQUEST:
return {
data: null,
...initState,
isLoading: true,
error: null,
}
case FETCH_SUCCESS:
return {
...initState,
isLoading: false,
error: null,
data: action.payload,
}
case FETCH_FAILURE:
return {
...initState,
isLoading: false,
error: action.error,
}
default:
throw new Error()
}
}

/**
* @param {*} requestFn custom fetch function, e.g: (data) => axios('/xxx', data)
* @param {*} initState setInit state, defaultValue: undefined
* @return {array} [state, memoizedFetchDateApi] state: { data, isLoading, error, ... }
*/
export default useFetchData = (requestFn, initState) => {
const [state, dispatch] = useReducer(fetchDataReducer, initState)

const fetchData = async (params) => {
dispatch({ type: FETCH_REQUEST })
try {
const result = await requestFn(params)
dispatch({ type: FETCH_SUCCESS, payload: result })
} catch (error) {
dispatch({ type: FETCH_FAILURE, error })
}
}

const memoizedFetchDateApi = useCallback(fetchData, [])
return [state || {}, memoizedFetchDateApi]
}

33 changes: 33 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@jzone/react-request-hook",
"version": "0.1.0",
"description": "🐶 React hook for custom request,compatible with various lib, support redux",
"main": "index.js",
"author": "zhixiaoqiang",
"license": "MIT",
"scripts": {
"prod": "node scripts/prod",
"release": "node scripts/release",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"hook",
"react",
"request"
],
"repository": {
"type": "git",
"url": "[email protected]:zhixiaoqiang/eslint-config.git"
},
"peerDependencies": {
"react": "^16.9.0",
"react-dom": "^16.9.0"
},
"devDependencies": {
"chalk": "^2.4.2",
"dayjs": "^1.8.17",
"execa": "^3.2.0",
"inquirer": "^7.0.0",
"semver": "^6.3.0"
}
}
45 changes: 45 additions & 0 deletions scripts/bump-version.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const inquirer = require('inquirer')
const semver = require('semver')
const currentVersion = require('../package.json').version

module.exports = async function bumpVersion () {
console.log(`Current version: ${currentVersion}`)

const bumps = ['patch', 'minor', 'major']
const versions = {}
bumps.forEach((b) => {
versions[b] = semver.inc(currentVersion, b)
})
const bumpChoices = bumps.map(b => ({
name: `${b} (${versions[b]})`,
value: b,
}))

const { bump, customVersion } = await inquirer.prompt([
{
name: 'bump',
message: 'Select release type:',
type: 'list',
choices: [...bumpChoices, { name: 'custom', value: 'custom' }],
},
{
name: 'customVersion',
message: 'Input version:',
type: 'input',
when: answers => answers.bump === 'custom',
},
])

const version = customVersion || versions[bump]

const { isConfirm } = await inquirer.prompt([
{
name: 'isConfirm',
message: `Confirm releasing ${version}?`,
type: 'confirm',
},
])
if (isConfirm) process.env.VERSION = version

return isConfirm
}
26 changes: 26 additions & 0 deletions scripts/prod.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const chalk = require('chalk')
const execa = require('execa')
const bumpVersion = require('./bump-version')

const [ type ] = process.argv.slice(2)

;(async () => {
console.log('publish start...')
const isConfirm = await bumpVersion()
const stdio = { stdio: 'inherit' }
if (isConfirm) {
await execa('yarn', ['release'], stdio)
if (type === 'tag') {
const version = process.env.VERSION
await execa('yarn', ['publish', '--tag', version], stdio)
} else {
await execa('yarn', ['publish'], stdio)
}
console.log(chalk.green('publish successful.'))
}
})().catch((err) => {
console.log(err)
err.stderr && console.error(err.stderr)
err.stdout && console.error(err.stdout)
process.exit(1)
})
Loading

0 comments on commit 9345a5b

Please sign in to comment.