import { push, register } from '@mtyk/dev-client' import { BaseActionSpec } from '@mtyk/dev-core' import { Optional } from '@mtyk/types' import { useEffect, useId, useState } from 'react' let idsToHooks = new Map void>() export interface ReactStateAction extends BaseActionSpec { hookId: string value: any } const type = 'react/setState' const handler = register({ type, runner: async (action, context) => { idsToHooks.get(action.hookId)!(action.value) }, prepare: async (action, context) => { const { hookId } = action const hook = idsToHooks.get(hookId) return idsToHooks.has(hookId) }, }) export default function useDevState( defaultValue: Optional, config: { name?: string } = {} ) { const id = useId() const [state, setState] = useState(defaultValue) useEffect(() => { idsToHooks.set(id, setState) return () => { idsToHooks.delete(id) } }, [setState]) function setState2(value: T) { setState(value) handler.push({ hookId: id, value, name: `setState (${config.name})`, }) } return [state, setState2] as const }