Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Zamaletdinov committed Jul 19, 2020
0 parents commit 04e839f
Show file tree
Hide file tree
Showing 16 changed files with 4,470 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
18 changes: 18 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint",
"prettier"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier/@typescript-eslint",
"plugin:react-hooks/recommended"
],
"rules": {
"prettier/prettier": "warn",
"max-len": "off"
}
}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
yarn-error.log
node_modules
coverage
12 changes: 12 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"semi": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 120,
"tabWidth": 2,
"arrowParens": "avoid",
"jsxSingleQuote": false,
"jsxBracketSameLine": false,
"quoteProps": "preserve",
"endOfLine": "lf"
}
5 changes: 5 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
language: node_js
node_js:
- 13
- 12
- 10
21 changes: 21 additions & 0 deletions LICENCE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2015-20 Renat Zamaletdinov <[email protected]>

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:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

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.
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
[![View on NPM](http://img.shields.io/npm/v/use-partial-state.svg)](https://www.npmjs.com/package/use-partial-state)
[![Build Status](https://travis-ci.com/Zamaletdinov/use-partial-state.svg?branch=master)](https://travis-ci.com/Zamaletdinov/use-partial-state)
[![Dependencies Status](https://david-dm.org/Zamaletdinov/use-partial-state/status.svg)](https://david-dm.org/Zamaletdinov/use-partial-state)

# use-partial-state

This library was built on top of React's useState hook that allows to ease partial state updates

## Usage

```ts
import { usePartialState } from 'use-partial-state';

type ComplexObject = { index: number; value: string };
const initialValue: ComplexObject = { index: 1, value: 'initial value' };
const newValue: ComplexObject = { index: 2, value: 'new value' };
const partialUpdate: Partial<ComplexObject> = { value: 'updated value' };

const [complexObject, setComplexObject, updateComplexObject] = usePartialState<ComplexObject>(initialValue);
console.log(complexObject);
// { index: 1, value: 'initial value' }

setComplexObject(newValue);
console.log(complexObject);
// { index: 2, value: 'new value' }

updateComplexObject(partialUpdate);
console.log(complexObject);
// { index: 2, value: 'updated value' }
```

If the `initialValue` or previous state is undefined then partial update value will be used as final one:

```ts
import { usePartialState } from 'use-partial-state';

type ComplexObject = { index: number; value: string };
const partialUpdate: Partial<ComplexObject> = { value: 'updated value' };

const [complexObject, setComplexObject, updateComplexObject] = usePartialState<ComplexObject>();

updateComplexObject(partialUpdate);
console.log(complexObject);
// { value: 'updated value' }
```
6 changes: 6 additions & 0 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Dispatch, SetStateAction } from 'react';
/**
* Returns a stateful value, and a functions to set and update it.
*/
export declare function usePartialState<S>(initialValue: S): [S, Dispatch<SetStateAction<S>>, (updated: Partial<S>) => void];
export declare function usePartialState<S = undefined>(initialValue?: S): [S | undefined, Dispatch<SetStateAction<S | undefined>>, (updated: Partial<S>) => void];
24 changes: 24 additions & 0 deletions dist/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
function usePartialState(initialValue) {
var _a = react_1.useState(initialValue), state = _a[0], setState = _a[1];
var partialSetState = react_1.useCallback(function (updated) {
setState(function (prev) {
return prev ? __assign(__assign({}, prev), updated) : __assign({}, updated);
});
}, []);
return [state, setState, partialSetState];
}
exports.usePartialState = usePartialState;
4 changes: 4 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
49 changes: 49 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{
"name": "use-partial-state",
"version": "1.0.0",
"description": "React's useState hook with easier partial updates",
"main": "dist/index.js",
"repository": "https://github.com/Zamaletdinov/use-partial-state.git",
"bugs": {
"url": "https://github.com/Zamaletdinov/use-partial-state/issues"
},
"homepage": "https://github.com/Zamaletdinov/use-partial-state",
"author": "Renat Zamaletdinov <[email protected]>",
"license": "MIT",
"keywords": [
"react",
"hook",
"useState",
"state",
"update",
"partial"
],
"engines": {
"node": ">=10"
},
"dependencies": {
"react": "^16.13.1"
},
"devDependencies": {
"@testing-library/react-hooks": "^3.3.0",
"@types/jest": "^26.0.5",
"@types/react": "^16.9.43",
"@typescript-eslint/eslint-plugin": "^3.6.1",
"@typescript-eslint/parser": "^3.6.1",
"eslint": "^7.5.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-react-hooks": "^4.0.8",
"jest": "^26.1.0",
"prettier": "^2.0.5",
"react-test-renderer": "^16.13.1",
"ts-jest": "^26.1.3",
"typescript": "^3.9.7"
},
"scripts": {
"build": "yarn tsc",
"test": "yarn jest",
"test-coverage": "yarn jest --collect-coverage",
"lint": "yarn eslint . --ext .ts --fix"
}
}
22 changes: 22 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Dispatch, SetStateAction, useCallback, useState } from 'react';

/**
* Returns a stateful value, and a functions to set and update it.
*/
export function usePartialState<S>(initialValue: S): [S, Dispatch<SetStateAction<S>>, (updated: Partial<S>) => void];
export function usePartialState<S = undefined>(
initialValue?: S
): [S | undefined, Dispatch<SetStateAction<S | undefined>>, (updated: Partial<S>) => void];
export function usePartialState<S>(
initialValue?: S
): [S | undefined, Dispatch<SetStateAction<S | undefined>>, (updated: Partial<S>) => void] {
const [state, setState] = useState(initialValue);

const partialSetState = useCallback((updated: Partial<S>) => {
setState(prev => {
return prev ? { ...prev, ...updated } : ({ ...updated } as S);
});
}, []);

return [state, setState, partialSetState];
}
64 changes: 64 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import React from 'react';
import { act, renderHook } from '@testing-library/react-hooks';

import { usePartialState } from '../src/index';

describe('usePartialState tests', () => {
type CompexObject = { index: number; value: string };
const initalObj: CompexObject = { index: 1, value: 'initial value' };

it('check initialization', () => {
const useStateMock = jest.spyOn(React, 'useState');
const useCallbackMock = jest.spyOn(React, 'useCallback');
renderHook(() => usePartialState<CompexObject>());

expect(useStateMock).toHaveBeenCalledTimes(1);
expect(useCallbackMock).toHaveBeenCalledTimes(1);

useStateMock.mockRestore();
useCallbackMock.mockRestore();
});

it('check setState', () => {
const newObj: CompexObject = { index: 2, value: 'new value' };
const { result } = renderHook(() => usePartialState(initalObj));

expect(result.current[0]).toBe(initalObj);

act(() => {
result.current[1](newObj);
});

expect(result.current[0]).toBe(newObj);
});

describe('check partialSetState', () => {
it('initial object is defined', () => {
const newValue = 'update value';
const expectedObj: CompexObject = { ...initalObj, value: newValue };
const { result } = renderHook(() => usePartialState(initalObj));

expect(result.current[0]).toBe(initalObj);

act(() => {
result.current[2]({ value: newValue });
});

expect(result.current[0]).toStrictEqual(expectedObj);
});

it('initial object is undefined', () => {
const newValue = 'update value';
const partialUpdate: Partial<CompexObject> = { value: newValue };
const { result } = renderHook(() => usePartialState<CompexObject>());

expect(result.current[0]).toBeUndefined();

act(() => {
result.current[2](partialUpdate);
});

expect(result.current[0]).toStrictEqual(partialUpdate);
});
});
});
13 changes: 13 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"sourceMap": false,
"outDir": "dist",
"strict": true,
"esModuleInterop": true
},
"include": ["src"],
"exclude": ["node_modules", "dist", "tests"]
}
Loading

0 comments on commit 04e839f

Please sign in to comment.