1.0.2 • Published 3 years ago

use-partial-state v1.0.2

Weekly downloads
14
License
MIT
Repository
github
Last release
3 years ago

View on NPM Build Status Dependencies Status

use-partial-state

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

Usage

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:

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' }