Skip to content

Commit

Permalink
feat(createGlobalState): 添加 watchStateImmediate
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 13, 2021
1 parent 0ce7087 commit 5452019
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/react/createGlobalState.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@ describe('createGlobalState', () => {
expect(cb).toBeCalled().toBeCalledTimes(2).toBeCalledWith('Jay2', 'Jay')
})

test('watchStateImmediate 正常', () => {
const cb = jest.fn()
const off = useGlobalName.watchStateImmediate(cb)
expect(cb).toBeCalled().toBeCalledTimes(1).toBeCalledWith('', undefined)
useGlobalName.setState('Jay')
expect(cb).toBeCalled().toBeCalledTimes(2).toBeCalledWith('Jay', '')
useGlobalName.setState('Jay2')
expect(cb).toBeCalled().toBeCalledTimes(3).toBeCalledWith('Jay2', 'Jay')
off()
expect(cb).toBeCalled().toBeCalledTimes(3).toBeCalledWith('Jay2', 'Jay')
})

test('跨组件状态共享正常', () => {
const { result: result1 } = renderHook(() => useGlobalName())
const { result: result2 } = renderHook(() => useGlobalName())
Expand Down
11 changes: 11 additions & 0 deletions src/react/createGlobalState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export interface CreateGlobalStateResult<
getState(): S
setState(nextState: SetStateAction<S>): void
watchState(callback: (nextState: S, prevState: S) => any): () => void
watchStateImmediate(callback: (nextState: S, prevState: S) => any): () => void
}

export function createGlobalState<S extends CreateGlobalStateState, R = never>(
Expand Down Expand Up @@ -80,6 +81,15 @@ export function createGlobalState<S extends CreateGlobalStateState, R = never>(
) => () => void = callback => {
return bus.on('setGlobalState', callback)
}
const watchGlobalStateImmediate: (
callback: (
nextGlobalState: S | undefined,
prevGlobalState: S | undefined,
) => any,
) => () => void = callback => {
callback(initialState, undefined)
return bus.on('setGlobalState', callback)
}
const useCustomResult = typeof customResult === 'function'
const useGlobalState: CreateGlobalStateResult<S | undefined, R> = (() => {
const [state, setState] = useState(currentGlobalState)
Expand All @@ -94,5 +104,6 @@ export function createGlobalState<S extends CreateGlobalStateState, R = never>(
useGlobalState.getState = getGlobalState
useGlobalState.setState = setGlobalState
useGlobalState.watchState = watchGlobalState
useGlobalState.watchStateImmediate = watchGlobalStateImmediate
return useGlobalState
}

0 comments on commit 5452019

Please sign in to comment.