https://github.com/termosa/use-patch
Track diff when changing objects
https://github.com/termosa/use-patch
Last synced: about 1 year ago
JSON representation
Track diff when changing objects
- Host: GitHub
- URL: https://github.com/termosa/use-patch
- Owner: termosa
- Created: 2021-10-31T09:33:32.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2023-08-11T01:03:49.000Z (almost 3 years ago)
- Last Synced: 2025-03-18T15:47:20.767Z (about 1 year ago)
- Language: TypeScript
- Size: 519 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# use-patch
> Track diff when changing objects
[](https://www.npmjs.com/package/use-patch) [](https://standardjs.com)
## Install
```bash
npm install --save use-patch
```
## Usage
```tsx
import * as React from 'react'
import usePatch from 'use-patch'
// Or: import { usePatch } from 'use-patch'
const Example = () => {
const {
diff, // The list of properties that are different from the origin object
value, // The origin object with patches applied to it
changed, // Boolean value that shows if diff contains changes
apply, // Function that adds changes to the origin object
set, // Function that defines the resulting object (the diff will be calculated from the origin and given object)
reset, // Function that resets all changes
} = usePatch(
origin, // The origin object to be compared with stored changes
);
// ...
};
```
## Examples
### Using it to track changed properties of the profile
[Source code](https://github.com/termosa/use-patch/blob/master/example/src/ProfileEditingExample.js)
```tsx
const ProfileEditingExample = () => {
const profile = { firstName: "Jeff", lastName: "Adams" };
const profilePatch = usePatch(profile);
return (
Origin
{JSON.stringify(profile, null, 2)}
Editor
First name
profilePatch.apply({ firstName: e.target.value })
}
/>
Last name
profilePatch.apply({ lastName: e.target.value })}
/>
Age
profilePatch.apply({ age: +e.target.value || undefined })
}
/>
The diff
{JSON.stringify(profilePatch.diff, null, 2)}
);
};
```
### Example of collecting data for PUT request
```tsx
import api from './api';
const ProfilePage = ({ profile }) => {
const profilePatch = usePatch(profile);
return (
api.put(profilePatch.diff)}
/>
);
};
```
## License
MIT © [termosa](https://github.com/termosa)
---
This hook is created using [create-react-hook](https://github.com/hermanya/create-react-hook).