Skip to content

Commit

Permalink
feat: support setting a new value using a setter function
Browse files Browse the repository at this point in the history
  • Loading branch information
StyleShit committed Aug 2, 2024
1 parent ee30927 commit daddcb3
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/flat-plums-itch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'reatom': patch
---

Support setting a new value using a setter function
11 changes: 11 additions & 0 deletions src/__tests__/atom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@ describe('atom', () => {
expect(countAtom.get()).toBe(1);
});

it('should set a new value using a function', () => {
// Arrange.
const countAtom = atom(0);

// Act.
countAtom.set((prev) => prev + 1);

// Assert.
expect(countAtom.get()).toBe(1);
});

it('should notify subscribers', () => {
// Arrange.
const countAtom = atom(0);
Expand Down
7 changes: 5 additions & 2 deletions src/atom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ export function atom<T>(initialValue: T) {

const get = () => value;

const set = (newValue: T) => {
value = newValue;
const set = (newValue: T | ((prev: T) => T)) => {
value =
typeof newValue === 'function'
? (newValue as (prev: T) => T)(value)
: newValue;

notify();
};
Expand Down

0 comments on commit daddcb3

Please sign in to comment.