Skip to content

Commit 162dda5

Browse files
committed
chore: add use.uncontrolled / use.valuesstate
1 parent bfeba10 commit 162dda5

File tree

22 files changed

+600
-1
lines changed

22 files changed

+600
-1
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ should be named as `use.{{lowerCase}}`, eg. `@rp/use.i18n`.
5959
- [@rcp/hoc.uncontrolled](packages/hoc.uncontrolled) - The high order component for creating uncontrolled component
6060
- [@rcp/use.i18n](packages/use.i18n) - A react hook for using i18n
6161
- [@rcp/use.i18ncontext](packages/use.i18ncontext) - A react hook for using i18n provider/consumer
62+
- [@rcp/use.valuesstate](packages/use.valuesstate) - The useful methods exported for values state
63+
- [@rcp/use.uncontrolled](packages/use.uncontrolled) - Make props.value piped to state, and exposes `onChange`, make react component is **uncontrolled & controlled**
6264
- [@rcp/util.createlogger](packages/util.createlogger) - Create namespace isomorphic logger
6365
- [@rcp/util.createmount](packages/util.createmount) - The utility for creating mountable view
6466
- [@rcp/util.displayname](packages/util.displayname) - The utility for getting display name

package-lock.json

Lines changed: 45 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
"devDependencies": {
4141
"@commitlint/cli": "^7.1.2",
4242
"@commitlint/config-conventional": "^7.1.2",
43+
"@testing-library/react-hooks": "^3.4.1",
4344
"@types/enzyme": "^3.1.13",
4445
"@types/jest": "^23.3.1",
4546
"@types/node": "^10.9.4",
@@ -79,6 +80,7 @@
7980
"puppeteer": "^2.1.1",
8081
"react": "^16.13.1",
8182
"react-dom": "^16.13.1",
83+
"react-test-renderer": "^16.13.1",
8284
"rimraf": "^2.6.2",
8385
"ts-jest": "^23.1.4",
8486
"ts-loader": "^6.2.2",

packages/__template/template/package.json.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ module.exports = ({ _, name, description }) => {
2121
dev: 'npm run dist -- -w',
2222
prepublishOnly: 'npm run dist',
2323
version: 'npm run doc',
24-
doc: 'documentation --markdown-toc=false readme index.js -a public -s "API" && git add README.md'
24+
doc: 'documentation --markdown-toc=false readme dist/es/index.js -a public -s "API" && git add README.md'
2525
},
2626
repository: {
2727
type: 'git',

packages/use.uncontrolled/.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
**/*.js
2+
!jest.config.js

packages/use.uncontrolled/.npmignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
index.ts
2+
index.tsx

packages/use.uncontrolled/License

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
MIT License
2+
3+
Copyright (c) imcuttle <[email protected]>
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6+
7+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8+
9+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

packages/use.uncontrolled/README.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# @rcp/use.uncontrolled
2+
3+
[![NPM version](https://img.shields.io/npm/v/@rcp/use.uncontrolled.svg?style=flat-square)](https://www.npmjs.com/package/@rcp/use.uncontrolled)
4+
[![NPM Downloads](https://img.shields.io/npm/dm/@rcp/use.uncontrolled.svg?style=flat-square&maxAge=43200)](https://www.npmjs.com/package/@rcp/use.uncontrolled)
5+
6+
Make props.value piped to state, and exposes `onChange`, make react component is **uncontrolled & controlled**
7+
8+
## Installation
9+
10+
```bash
11+
npm install @rcp/use.uncontrolled
12+
# or use yarn
13+
yarn add @rcp/use.uncontrolled
14+
```
15+
16+
## Usage
17+
18+
```javascript
19+
import useUncontrolled from '@rcp/use.uncontrolled'
20+
```
21+
22+
## API
23+
24+
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
25+
26+
### useUncontrolled
27+
28+
#### Parameters
29+
30+
- `value` {T} - Piped value
31+
- `defaultValue` {T} - Initialize value firstly
32+
- `onChange` {(value: T) => void} - Bind `onChange` handler when value updating
33+
- `useEffect` {typeof React.useLayoutEffect}
34+
35+
#### Examples
36+
37+
```javascript
38+
function Input({ value, onChangeValue, defaultValue }) {
39+
const [valueState, setValue] = useUncontrolled({ value, onChange: onChangeValue, defaultValue })
40+
41+
return <input type="text" value={valueState} onChange={evt => setValue(evt.target.value)} />
42+
}
43+
```
44+
45+
Returns **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)** `[T, ((value: T) => T | T) => void]`
46+
47+
## Related
48+
49+
## Authors
50+
51+
This library is written and maintained by imcuttle, <a href="mailto:[email protected]">[email protected]</a>.
52+
53+
## License
54+
55+
MIT
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import useUncontrolled from '..'
2+
import * as TestRenderer from 'react-test-renderer'
3+
import { renderHook, act } from '@testing-library/react-hooks'
4+
import * as React from 'react'
5+
6+
describe('useUncontrolled', () => {
7+
const Test = React.forwardRef(({ value, defaultValue, onChange }: any, ref) => {
8+
const [stateValue, setValue] = useUncontrolled({ value, defaultValue, onChange })
9+
React.useImperativeHandle(
10+
ref,
11+
() => {
12+
return {
13+
stateValue,
14+
setValue
15+
}
16+
},
17+
[stateValue, setValue]
18+
)
19+
20+
return stateValue
21+
})
22+
23+
it('value / props sync', () => {
24+
const ref = React.createRef<any>()
25+
const onChange = jest.fn(() => {})
26+
const testRenderer = TestRenderer.create(<Test ref={ref} onChange={onChange} defaultValue={1} />)
27+
28+
expect(testRenderer.toJSON()).toMatchInlineSnapshot(`"1"`)
29+
expect(ref.current.stateValue).toMatchInlineSnapshot(`1`)
30+
expect(onChange).not.toBeCalled()
31+
32+
// update state inner
33+
act(() => {
34+
ref.current.setValue(2)
35+
})
36+
expect(onChange).toBeCalledWith(2)
37+
expect(testRenderer.toJSON()).toMatchInlineSnapshot(`"2"`)
38+
expect(ref.current.stateValue).toMatchInlineSnapshot(`2`)
39+
40+
// update state
41+
testRenderer.update(<Test ref={ref} onChange={onChange} value={3} />)
42+
expect(testRenderer.toJSON()).toMatchInlineSnapshot(`"3"`)
43+
expect(ref.current.stateValue).toMatchInlineSnapshot(`3`)
44+
expect(onChange).toBeCalledWith(3)
45+
})
46+
47+
it('should do not call onChange firstly', function() {
48+
const onChange = jest.fn(() => {})
49+
const testRenderer = TestRenderer.create(<Test onChange={onChange} value={1} />)
50+
expect(onChange).not.toBeCalled()
51+
52+
testRenderer.update(<Test onChange={onChange} value={1} />)
53+
expect(onChange).not.toBeCalled()
54+
55+
testRenderer.update(<Test onChange={onChange} value={2} />)
56+
expect(onChange).toHaveBeenCalledTimes(1)
57+
})
58+
})

packages/use.uncontrolled/index.ts

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/**
2+
* @file index.ts
3+
* @author imcuttle
4+
*
5+
*/
6+
7+
import * as React from 'react'
8+
9+
export function useUncontrolledCore<T = any>(
10+
propValue?: T,
11+
{
12+
initialValue = propValue,
13+
useEffect = React.useEffect,
14+
onChange
15+
}: { initialValue?: T; useEffect?: typeof React.useEffect; onChange?: (value: T) => void } = {}
16+
): [T | undefined, (newValue: ((value: T) => T) | T) => void] {
17+
const [value, setStateValue] = React.useState(initialValue)
18+
const setValueFinal = React.useCallback(
19+
(newValue: Function | boolean | any) => {
20+
if (typeof newValue === 'function') {
21+
newValue = newValue(value)
22+
}
23+
if (value === newValue) {
24+
return
25+
}
26+
setStateValue(newValue)
27+
onChange && onChange(newValue)
28+
},
29+
[value, onChange, setStateValue]
30+
)
31+
32+
useEffect(
33+
() => {
34+
if (typeof propValue !== 'undefined') {
35+
setValueFinal(propValue)
36+
}
37+
},
38+
[propValue, setValueFinal]
39+
)
40+
41+
return [value, setValueFinal]
42+
}
43+
44+
/**
45+
* @public
46+
* @name useUncontrolled
47+
* @param [value] {T} - Piped value
48+
* @param [defaultValue] {T} - Initialize value firstly
49+
* @param [onChange] {(value: T) => void} - Bind `onChange` handler when value updating
50+
* @param [useEffect] {typeof React.useLayoutEffect}
51+
* @returns {Array} `[T, ((value: T) => T | T) => void]`
52+
* @example
53+
* function Input({value, onChangeValue, defaultValue}) {
54+
* const [valueState, setValue] = useUncontrolled({value, onChange: onChangeValue, defaultValue})
55+
*
56+
* return <input type='text' value={valueState} onChange={evt => setValue(evt.target.value)} />
57+
* }
58+
*/
59+
export default function useUncontrolled<T = any>({
60+
value,
61+
defaultValue,
62+
onChange,
63+
useEffect = React.useLayoutEffect
64+
}: {
65+
useEffect?: typeof React.useEffect
66+
value?: T
67+
defaultValue?: T
68+
onChange?: (value: T) => void
69+
}) {
70+
let initialValue = value
71+
if (defaultValue) {
72+
initialValue = typeof value === 'undefined' ? defaultValue : value
73+
}
74+
75+
return useUncontrolledCore<T>(value, {
76+
initialValue,
77+
useEffect,
78+
onChange
79+
})
80+
}

0 commit comments

Comments
 (0)