From 395e82b03bb41c4e7bc849bfc4cfb50611fbae3b Mon Sep 17 00:00:00 2001 From: streamich Date: Mon, 29 Oct 2018 18:42:47 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20improve=20useCounter=20i?= =?UTF-8?q?nterface?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BREAKING CHANGE: useCounter interface changed --- src/__stories__/useCounter.story.tsx | 9 ++++++-- src/useCounter.ts | 31 ++++++++++++++++++++++------ src/useGetSet.ts | 11 +++++----- 3 files changed, 37 insertions(+), 14 deletions(-) diff --git a/src/__stories__/useCounter.story.tsx b/src/__stories__/useCounter.story.tsx index 1c842e1092..a888a732b0 100644 --- a/src/__stories__/useCounter.story.tsx +++ b/src/__stories__/useCounter.story.tsx @@ -4,13 +4,18 @@ import {useCounter} from '..'; import ShowDocs from '../util/ShowDocs'; const Demo = () => { - const [value, inc, set] = useCounter(); + const [value, {inc, dec, get, set, reset}] = useCounter(5); return (
-
{value}
+
{value} is {get()}
+ + + + +
); }; diff --git a/src/useCounter.ts b/src/useCounter.ts index 975efed199..1a8dcf246a 100644 --- a/src/useCounter.ts +++ b/src/useCounter.ts @@ -1,12 +1,31 @@ -import {useState} from './react'; +import useGetSet from './useGetSet'; +import {useCallback} from './react'; -export type Increment = (inc?: number) => void; -export type Set = (value: number) => void; +export interface CounterActions { + inc: (delta?: number) => void; + dec: (delta?: number) => void; + get: () => number; + set: (value: number) => void; + reset: (value?: number) => void; +} -const useCounter = (initialValue: number = 0): [number, Increment, Set] => { - const [value, set] = useState(initialValue); +const useCounter = (initialValue: number = 0): [number, CounterActions] => { + const [get, set] = useGetSet(initialValue); + const inc = useCallback((delta: number = 1) => set(get() + delta), []); + const dec = useCallback((delta: number = 1) => inc(-delta), []); + const reset = useCallback((value: number = initialValue) => { + initialValue = value; + set(value); + }, []); + const actions = { + inc, + dec, + get, + set, + reset, + }; - return [value, (inc = 1) => set(value + inc), set]; + return [get(), actions]; }; export default useCounter; diff --git a/src/useGetSet.ts b/src/useGetSet.ts index 6e76bbb378..e9191c84ab 100644 --- a/src/useGetSet.ts +++ b/src/useGetSet.ts @@ -1,15 +1,14 @@ -import {useRef} from './react'; +import {useRef, useCallback} from './react'; import useUpdate from './useUpdate'; const useGetSet = (initialValue: T): [() => T, (value: T) => void] => { - const update = useUpdate(); let state = useRef(initialValue); - - const get = () => state.current; - const set = (value: T) => { + const update = useUpdate(); + const get = useCallback(() => state.current, []); + const set = useCallback((value: T) => { state.current = value; update(); - }; + }, []); return [get, set]; };