devtools: minor fixes (#720)

This commit is contained in:
Devansh Jethmalani 2021-12-23 06:33:07 +05:30 committed by GitHub
parent 0aeaf7f050
commit cb99a36c59
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 24 deletions

View File

@ -182,17 +182,39 @@ export const devtools =
)
}
const setStateFromDevtools: SetState<S> = (...a) => {
const originalIsRecording = isRecording
isRecording = false
set(...a)
isRecording = true
isRecording = originalIsRecording
}
const initialState = fn(api.setState, get, api)
extension.init(initialState)
if (api.dispatchFromDevtools && typeof api.dispatch === 'function') {
let didWarnAboutReservedActionType = false
const originalDispatch = api.dispatch
api.dispatch = (...a: any[]) => {
if (a[0].type === '__setState' && !didWarnAboutReservedActionType) {
console.warn(
'[zustand devtools middleware] "__setState" action type is reserved ' +
'to set state from the devtools. Avoid using it.'
)
didWarnAboutReservedActionType = true
}
;(originalDispatch as any)(...a)
}
}
extension.subscribe((message: any) => {
switch (message.type) {
case 'ACTION':
if (typeof message.payload !== 'string') {
console.error(
'[zustand devtools middleware] Unsupported action format'
)
return
}
return parseJsonThen<{ type: unknown; state?: PartialState<S> }>(
message.payload,
(action) => {
@ -245,21 +267,6 @@ export const devtools =
}
})
if (api.dispatchFromDevtools && typeof api.dispatch === 'function') {
let didWarnAboutReservedActionType = false
const originalDispatch = api.dispatch
api.dispatch = (...a: any[]) => {
if (a[0].type === '__setState' && !didWarnAboutReservedActionType) {
console.warn(
'[zustand devtools middleware] "__setState" action type is reserved ' +
'to set state from the devtools. Avoid using it.'
)
didWarnAboutReservedActionType = true
}
;(originalDispatch as any)(...a)
}
}
return initialState
}

View File

@ -187,14 +187,7 @@ describe('when it receives an message of type...', () => {
}).not.toThrow()
expect(console.error).toHaveBeenLastCalledWith(
'[zustand devtools middleware] Could not parse the received json',
(() => {
try {
JSON.parse({ name: 'increment', args: [] } as unknown as string)
} catch (e) {
return e
}
})()
'[zustand devtools middleware] Unsupported action format'
)
expect(api.getState()).toBe(initialState)
@ -489,3 +482,18 @@ it('works in non-browser env', () => {
global.window = originalWindow
})
it('preserves isRecording after setting from devtools', () => {
const api = create(devtools(() => ({ count: 0 })))
;(extensionSubscriber as (message: any) => void)({
type: 'DISPATCH',
payload: { type: 'PAUSE_RECORDING' },
})
;(extensionSubscriber as (message: any) => void)({
type: 'ACTION',
payload: '{ "type": "__setState", "state": { "foo": "bar" } }',
})
api.setState({ count: 1 })
expect(extension.send).not.toBeCalled()
})